replace <constructor-arg> with Spring Annotation

Roberto de Santis picture Roberto de Santis · Jan 6, 2011 · Viewed 14.2k times · Source

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

I have this constructor:

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

and i need to inject that in my Facade:

@Inject
private GenericDAO<Auto, Long> autoDao;

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

Thank you in advance

[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?

Answer

Sean Patrick Floyd picture Sean Patrick Floyd · Jan 6, 2011

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

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

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

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;
    }

}

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.


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;
}