I actually need to create beans out of the config file.My problem is I need to specify some of the props as variables
Please note that the scope of this bean is prototype, so I will want to create multiple instances of this bean, each with a different property "name".Code:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="testBean" class="com.TestBeanProps" lazy-init="true" scope="prototype"> <property name="name"> <value>${name}</value> </property> </bean> </beans>
The way I am doing it currently is
The thing about this code is I am creating a new context every time I need to create a new bean. This is not desired. Is it possible to use the same context over and over to create beans out of it?Code:public static void main(String[] args) { XmlBeanFactory ctx = new XmlBeanFactory(new FileSystemResource("asyncDynamicConsumer.xml")); XmlBeanFactory ctx2 = new XmlBeanFactory(new FileSystemResource("asyncDynamicConsumer.xml")); if(ctx == ctx2 || ctx.equals(ctx2)){ System.out.println("Both contexes are same"); }else{ System.out.println("Both contexes are diff"); } PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); Properties props = new Properties(); props.setProperty("name", "MyName"); props.setProperty("bla", "blabla"); cfg.setProperties(props); cfg.postProcessBeanFactory(ctx); TestBeanProps propers = (TestBeanProps) ctx.getBean("testBean"); System.out.println(propers.getName()); PropertyPlaceholderConfigurer cfg2 = new PropertyPlaceholderConfigurer(); Properties props2 = new Properties(); props2.setProperty("name", "YourName"); props2.setProperty("bla", "blabla"); cfg2.setProperties(props2); cfg2.postProcessBeanFactory(ctx2); TestBeanProps propers3 = (TestBeanProps) ctx2.getBean("testBean"); System.out.println(propers3.getName()); }
An alternate approach is
But I don't think this is springs friendly approach.Code:ClassPathApplicationContext ctx = new ClassPathApplicationContext("asyncDynamicConsumer.xml"); TestBeanProps propers = (TestBeanProps) ctx.getBean("testBean"); propers.setName("MyName"); TestBeanProps propers2 = (TestBeanProps) ctx.getBean("testBean"); propers2.setName("YourName");
Please help.


Reply With Quote
