在使用静态工厂类方法创建Bean实例的时候,class的属性一定要指定,但是class的属性并不是一定要指定Bean的实例的实现类,而是此实例的静态工厂类。因为spring需要知道用哪个工厂来创建Bean实例,另外还需要factory来指定静态工厂的方法名,spring将调用静态工厂的方法(可能包含一组参数),来返回一个Bean实例,一旦获得了指定Bean实例,spring后面的处理步骤与采用普通方法创建Bean实例则完全一样。需要注意的是,当使用静态工厂方法来创建Bean,这个factory-method必须要是静态的 。看代码如下。
这是一个Person类
package com.study.demo1;
public class Person {
private String personName;
private int personAge;
public Person(){
}
public Person(String personName,int personAge){
this.personAge=personAge;
this.personName=personName;
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public int getPersonAge() {
return personAge;
}
public void setPersonAge(int personAge) {
this.personAge = personAge;
}
@Override
public String toString() {
return "personName = " + personName + ", personAge = " + personAge;
}
}
这是一个工厂类,注意getInstance方法是静态的 所以 new对象也是要静态的
package com.study.demo1;
public class SingletonClass {
private static Person person=new Person("张三",18);
private SingletonClass(){
}
public static Person getInstance(){
return person;
}
}
看bean.xml的配置
<?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="hello" class="com.study.spring.HelloImp" ></bean> <bean id="singletonClass" class="com.study.demo1.SingletonClass" factory-method="getInstance"/> </beans>
在主方法中测试如下
package com.study.demo1; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext ctx=new ClassPathXmlApplicationContext("helloworld.xml"); Person person=(Person) ctx.getBean("singletonClass"); System.out.println(person); } }
返回结果如下
personName = 张三, personAge = 18
浙公网安备 33010602011771号