Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring autowire using annotations and a type defined in a properties file?

My goal is a framework where concrete types of beans can be easily changed by a properties file. I also prefer annotations to XML. Ideally I'd to use a combination of @Resource and SpEL like this:

@Resource(type="#{myProperties['enabled.subtype']}")
SomeInterface foo;

where I've loaded myProperties with a PropertiesFactoryBean or <util:properties> from a file that includes:

enabled.type = com.mycompany.SomeClassA; // which implements SomeInterface

This doesn't work because the argument of type must be a literal, i.e., no SpEL allowed. What's the best practice here?

Update: See my answer below.

like image 253
John Lehmann Avatar asked May 17 '12 20:05

John Lehmann


2 Answers

This is exactly the use case for Spring Java Configuration.

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-java

Or you can alternatively make a Factory.

Using: org.springframework.beans.factory.FactoryBean<SomeInterface>

The name of the bean that implements FactoryBean will be seen as a "SomeInterface" even though its not.

like image 65
Adam Gent Avatar answered Oct 02 '22 13:10

Adam Gent


I think it is not possible, the solution I tend to adopt is to use a factory that creates the different objects depending on a configuration property (enabled.type in your example).

A second alternative could be to use injection by name:

@Resource(name="beanName")

And last, if you use Spring 3.1+ you can try to use profiles, and have different bean sets in different profiles, if that solves your problem.

like image 35
Guido Avatar answered Oct 02 '22 15:10

Guido