This is my class :
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
PropertyPlaceholderConfigurer pph = new PropertyPlaceholderConfigurer();
pph.setLocations(new Resource[]{new ClassPathResource("one.properties"), new ClassPathResource("two.properties")});
context.addBeanFactoryPostProcessor(pph);
context.refresh();
Controller obj1 = (Controller) context.getBean("controller");
System.out.println(obj1.getMessage());
Controller2 obj2 = (Controller2) context.getBean("controller2");
System.out.println(obj2.getMessage());
System.out.println(obj2.getInteger());
This is the relevant xml configuration:
<bean id="controller" class="com.sample.controller.Controller">
<property name="message" value="${ONE_MESSAGE}"/>
</bean>
<bean id="controller2" class="com.sample.controller.Controller2">
<property name="message" value="${TWO_MESSAGE}"/>
<property name="integer" value="${TWO_INTEGER}"/>
</bean>
one.properties:
ONE_MESSAGE=ONE
two.properties:
TWO_MESSAGE=TWO
TWO_INTEGER=30
TWO_MESSAGE is assigned correctly as String TWO. I am getting NumberFormatException when injecting a TWO_INTEGER. Is there a way to achieve this without adding a setter that takes String and coverts it to int in Controller2 class?
The error :
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'controller2' defined in class path resource [beans.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'integer'; nested exception is java.lang.NumberFormatException: For input string: "${TWO_INTEGER}"
Thanks.
Probably your application falling in this line (please provide full stacketrace if i mistake):
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
because Spring can't parse ${TWO_INTEGER}
(this properties doesn't loaded in context as yet). So you can just move context initializing after properties loaded:
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
PropertyPlaceholderConfigurer pph = new PropertyPlaceholderConfigurer();
pph.setLocations(new Resource[]{new ClassPathResource("one.properties"), new ClassPathResource("two.properties")});
context.addBeanFactoryPostProcessor(pph);
context.setConfigLocation("beans.xml");
context.refresh();
Hope this help.