本文介绍了替换 <constructor-arg>带有 Spring 注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用注解替换构造函数参数?

there is a way to replace constructor-arg with Annotation?

我有这个构造函数:

public GenericDAOImpl(Class<T> type) {
    this.type = type;
}

我需要在我的 Facade 中注入它:

and i need to inject that in my Facade:

@Inject
private GenericDAO<Auto, Long> autoDao;

问题是我不知道如何在 costructor 中传递参数的值.

The problem is that i don't know how to pass the value of parameter in costructor.

提前致谢

[更多信息]我试着解释我的问题.

[More Info]I try to explain my problem.

<bean id="personDao" class="genericdao.impl.GenericDaoHibernateImpl">
        <constructor-arg>
            <value>genericdaotest.domain.Person</value>
        </constructor-arg>
</bean>

我只想使用注释转换该代码.有人可以解释一下吗?

I want convert that code using only annotation.Someone can explain how?

推荐答案

我认为 @Inject 单独没有帮助,你将不得不使用 @Qualifier 注释还有.

I think @Inject alone won't help, you will have to use a @Qualifier annotation also.

这是 Spring 参考的相关部分:
3.9.3 使用限定符微调基于注解的自动装配

Here's the relevant Section of the Spring Reference:
3.9.3 Fine-tuning annotation-based autowiring with qualifiers

如果我理解正确,您将不得不使用 @Qualifier 机制.

If I understand this correctly, you will have to use the @Qualifier mechanism.

如果你使用 Spring的@Qualifier注解,你大概可以内联做,像这样:

If you use Spring's @Qualifier annotation, you can probably do it inline, something like this:

@Repository
public class DaoImpl implements Dao{

    private final Class<?> type;

    public DaoImpl(@Qualifier("type") final Class<?> type){
        this.type = type;
    }

}

但是如果您使用 JSR-330 @Qualifier 注释,我猜您必须创建自己的标记为 @Qualifier 的自定义注释.

But if you use the JSR-330 @Qualifier annotation, I guess you will have to create your own custom annotation that is marked with @Qualifier.

另一种可能性是 @Value 注释.有了它,您可以使用表达式语言,例如像这样:

Another possibility would be the @Value annotation. With it you can use Expression Language, e.g. like this:

public DaoImpl(
    @Value("#{ systemProperties['dao.type'] }")
    final Class<?> type){
    this.type = type;
}

这篇关于替换 &lt;constructor-arg&gt;带有 Spring 注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 23:19