Here are the steps to do that:
1) First Step is to create a new custom object which will be dynamically attached to the Spring Context.
package com.milind.BeanAttach;
/**
*
* @author milind
*/
public class TestBean {
private String name;
public TestBean() {
}
private int age;
public TestBean(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Name: "+this.name+ " Age: "+ this.age;
}
}
2) Now we need to create our own custom BeanFactory by implementing the FactoryBean interface.
package com.milind.BeanAttach;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.FactoryBean;
/**
*
* @author milind
*/
public class AttachBean implements BeanNameAware, FactoryBean {
public static Map
public static Map
return beanMap;
}
public static void setBeanMap(Map
AttachBean.beanMap = beanMap;
}
private String beanName;
public void setBeanName(String arg0) {
System.out.println("In Set Bean Name .....");
this.beanName= arg0;
}
public Object getObject() throws Exception {
System.out.println("In get Object .....");
return beanMap.get(this.beanName);
}
public Class getObjectType() {
return beanMap.get(this.beanName).getClass();
}
public boolean isSingleton() {
return false;
}
}
3) Creating the applicationContext.xml
Here is the how the applicationContext.xml will look like:

4) Creating the Client to test
package com.milind.BeanAttach;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* @author milind
*/
public class BeanTest {
public static void main(String[] args) {
TestBean obj = new TestBean("Tanmay", 4);
AttachBean.beanMap.put("attach_object", obj);
ApplicationContext ctx = new ClassPathXmlApplicationContext("com/milind/BeanAttach/applicationContext.xml");
TestBean gotObj = (TestBean)ctx.getBean("attach_object");
print(gotObj.toString());
print("Assigning new Object .........................................");
AttachBean.beanMap.put("attach_object", new TestBean("Guest", 99));
gotObj = (TestBean)ctx.getBean("attach_object");
print(gotObj.toString());
}
private static void print(String s) {
System.out.println(s);
}
}
Now you can attach object of any type to the same bean id. Only you had to cast it appropriately when you get the object from context.
No comments:
Post a Comment