Sunday, 6 September 2015

Inject a java.util.Properties into a Spring Bean


Hard Coded

<bean id="adminUser" class="com.spring.InjectProperties">
       <!-- java.util.Properties -->
       <property name="emails">
              <props>
                     <prop key="admin">admin@nospam.com</prop>
                     <prop key="support">support@nospam.com</prop>
              </props>
       </property>
</bean>


From properties file

You can use “util:” namespace as well to create properties bean from properties file, and use bean reference for setter injection.

<util:properties id="emails" location="classpath:com/foo/emails.properties" />

Inject a property value into a Spring Bean using XML configurations

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

Inject a property value into a Spring Bean using annotations

@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.

Typically, @Autowired is used for by-type autowiring in Spring, and @Resource is used for by-name.

package com.abusecore.controller;
@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;

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...