Bean 的配置方式:
基于XML的方式配置bean.
- 通过全类名(反射)
- 通过工厂方法(静态工厂方法 & 实例工厂方法)
- FactoryBean 基于注解的方式配置bean.
工厂方法:
public class StaticFactory {
private static Map<String,Person> persons = new HashMap<String,Person>();
static{
persons.put("tom", new Person("tom",12));
persons.put("jack", new Person("jack",12));
}
//静态工厂方法。
public static Person getPerson(String name){
return persons.get(name);
}
}
//实例工厂,需要创建工厂本身,再调用工厂的实例(对象)方法来返回需要的对象本身。
public class InstanceFactory {
private Map<String,Person> persons = null;
public InstanceFactory(){
persons = new HashMap<String,Person>();
persons.put("haha", new Person("haha",18));
persons.put("xixi", new Person("xixi",18));
}
public Person getPerson(String name){
return persons.get(name);
}
}
通过静态工厂方法配置bean
<bean id="tom"
class="com.chai.lesson1.StaticFactory"
factory-method="getPerson">
<constructor-arg value="tom"></constructor-arg>
</bean>
通过实例工厂方法配置bean
<!-- 配置工厂本身-->
<bean id="instanceFactory" class="com.chai.lesson1.InstanceFactory">
</bean>
<!-- 配置需要的bean实例 factory-bean指向实例工厂的bean, factory-method实例工厂的方法名。-->
<bean id="xixi" factory-bean="instanceFactory" factory-method="getPerson">
<constructor-arg value="xixi"></constructor-arg>
</bean>
FactoryBean:通过factorybean 配置 bean的实例。property配置factorybean的属性值
XML文件:
<bean id="p1" class="com.chai.lesson1.PersonFactoryBean">
<property name="name" value="beanfactory..."></property>
</bean>
FactoryBean实现类:
public class PersonFactoryBean implements FactoryBean<Person> {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public Person getObject() throws Exception {
// TODO Auto-generated method stub
return new Person(name,30);
}
@Override
public Class<?> getObjectType() {
// TODO Auto-generated method stub
return Person.class;
}
@Override
public boolean isSingleton() {
// TODO Auto-generated method stub
return true;
}
}