Let’s say we have two beans qualified to be injected then we go for this.
Change code as below :
<context:annotation-config />
<bean id="address" class="com.javabykiran.Address">
<property name="landmark" value="park plaza"></property>
</bean>
<bean id="address1" class="com.javabykiran.Address">
<property name="landmark" value="park plaza"></property>
</bean>
<bean id="stu" class="com.javabykiran.Student" scope="singleton">
<property name="age" value="30"></property>
<property name="mobileNos">
<list>
<value>8888809416</value>
<value>9552343698</value>
</list>
</property>
</bean>
public class Student {
@Autowired
@Qualifier(value="address1")
Address address;
}
Now we will see how we can inject primitives from property files.
Change spConfig.xml as below.
We need to inform spring where is out properties file located.
Create property file in resources folder
Use annotation @value for injecting values.
Value may be multiple [comma separated ] or single
Client for invocation
We are using this for DB Connection in this case.
Spconfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:annotation-config />
<bean id= "propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>db.properties</value>
<!-- List other property files here -->
<!-- value>mail.properties</value -->
</list>
</property>
</bean>
<bean id="dbUtil" class="com.javabykiran.DBUtil" />
</beans>
DB.properties
jdbc.username=javabykiran
#try using comma as a separator. you can change it
#use split method in java while injecting
jdbc.portNos=3306,8880,9885
DBUtil.java
package com.javabykiran;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Value;
public class DBUtil {
@Value("${jdbc.username}")
String userName;
// use Expression language for this. need not to remember exact syntax.
// If comma is separator then no issue
// no need of split method
//@Value("#{'${jdbc.portNos}'.split('#')}")
@Value("${jdbc.portNos}")
String[] portNos;
@Override
public String toString() {
return "DBUtil [userName=" + userName + ", portNos=" + Arrays.toString(portNos) + "]";
}
}