1.定义实体类:
package cn.edu.tju;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class Person implements ApplicationContextAware {
private String username;
private String password;
private ApplicationContext applicationContext;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void init(){
this.username="new"+username;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext=applicationContext;
}
}
2.定义类,实现FactoryBean接口,其中泛型为上述实体类
package cn.edu.tju;
import org.springframework.beans.factory.FactoryBean;
public class MyFactoryBean implements FactoryBean<Person> {
@Override
public Person getObject() throws Exception {
Person p=new Person();
p.setUsername("Newton");
p.setPassword("newton");
return p;
}
@Override
public Class<?> getObjectType() {
return Person.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
3.配置上述FactoryBean的实现类MyFactoryBean到spring 容器:
<bean id="myFactoryBean" class="cn.edu.tju.MyFactoryBean"/>
4.在程序中通过getBean获取,并强转成实体类
Person p=(Person)applicationContext.getBean("myFactoryBean");
System.out.println(p.getUsername()+","+p.getPassword());
5.通过“&myFactoryBean"可以获取到MyFactoryBean 本身,而不是其所生产的对象:
MyFactoryBean myFactoryBean=(MyFactoryBean) applicationContext.getBean("&myFactoryBean");
容器创建完成后,实体类的对象并不存在,只有调用getBean(“myFactoryBean”)进行获取时才创建实体类对象。
通过getBean多次获取时,得到的是同一个实体类对象