jeudi 26 mars 2015

Spring: Unable to inject property using Environment from XML to JavaConfig

I am working on supporting a legacy Spring Java project that uses XML-based configuration. Injection from a property source is done like so:



<context:property-placeholder location="classpath:app.properties"/>


I am working on a new feature that is being implemented as a separate Spring project, serving as a dependency to the legacy project. To keep up with the times, that new project uses JavaConfig instead of XML-based configuration. As such, my class is annotated with @Configuration, has some @Bean methods in it, and does other logic to set up the classes in my project. I inject and load the Configuration by declaring it as a bean in the XML config:



<context:annotation-config/>
<beans:bean class="com.example.MyDefaultConfiguration"/>


There is a reliance in this JavaConfig on some injected properties. What I have read from various sources, such as this blog post and this SOF answer, is that this can be done by injecting an Environment instance into my JavaConfig class. Therefore I have this as an injected global field:



@Inject
private Environment environment;


And then I can do this in a @Bean method as needed:



String prop = environment.getProperty("my.property");


However, this property is not found in the environment and results in a value of null, despite it being clearly listed in my classpath's app.properties file. Instead, if I were to inject the property using the @Value annotation style, like shown below, then I do get the String variable to properly be injected into:



@Value("${my.property}")
private String prop;


I'm glad I was able to solve the problem, but I remain grossly curious as to why the injected Environment variable style did not work for me. It makes me worry that I mucked up some sort of configuration somewhere. Anyone have any ideas?


Aucun commentaire:

Enregistrer un commentaire