Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Util:Properties Injection via Annotations into a bean

If I have 2 .properties files setup in my Spring XML as so:

<util:properties id="serverProperties" location="file:./applications/MyApplication/server.properties"/> <util:properties id="someConfig" location="file:./applications/MyApplication/config.properties"/> 

How can I inject via annotations these properties files into a bean with java.util.Properties?

How can I grab specific properties via Spring annotations?

Cheers!

like image 552
NightWolf Avatar asked Aug 28 '11 04:08

NightWolf


People also ask

How do you inject Java Util properties into Spring beans?

Spring Bean + Properties + Annotation configuration example Create a configuration class and define the properties bean in it as shown below. Create a spring bean class and inject properties into it using @Autowired and @Qualifier annotations. Create main class and run application.

How do you inject annotations in Spring properties?

Spring get value from system property. You can set the system property on the Java command line using the -Dpropertyname=value syntax or at runtime using System. setProperty function. To inject the value from the system property, annotate your field using the @Value annotation with SpEL expression as below.


1 Answers

@Autowired @Qualifier("serverProperties") private Properties serverProperties; @Autowired @Qualifier("someConfig") private Properties otherProperties; 

or

@Resource(name = "serverProperties") private Properties serverProperties; @Resource(name = "someConfig") private Properties otherProperties; 

Typically, @Autowired is used for by-type autowiring in Spring, and @Resource is used for by-name. @Autowired+@Qualifier can double as by-name autowiring, but it's really meant for by-type autowiring with the ability to fine-tune the type.

like image 103
Ryan Stewart Avatar answered Sep 19 '22 17:09

Ryan Stewart