Bean配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<!-- 通过实现FactoryBean接口 配置bean -->
<bean id="cola" class="top.demo.test.spring2.WaterFactoryBean"></bean>
</beans>
测试用到的Water类
package top.demo.test.spring2;
public class Water {
public String name;
public int price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public Water(String name, int price) {
super();
this.name = name;
this.price = price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Water [name=" + name + ", price=" + price + "]";
}
}
实现FactoryBean的类
package top.demo.test.spring2;
import org.springframework.beans.factory.FactoryBean;
public class WaterFactoryBean implements FactoryBean<Water>{
@Override
public Water getObject() throws Exception {
//获得工厂创建的对象的接口方法
return new Water("可乐", 4);
}
@Override
public Class<?> getObjectType() {
// 返回对象的Class
return Water.class;
}
@Override
public boolean isSingleton() {
// 返回是否是单例的
//注意这个方法,如果返回true代表单例,即使getObject方法实现时是new(好像是每次调用会有新的地址,但是不是)
//也会得到同一个地址的对象(也就是 是不是单例取决于isSingleton方法,不必奇怪,有反射和动态代理 //框架设计者完全可以做到在getObject之前 检查isSingleton 也可以保存第一次new 出的地址 )
return true;
}
}
测试main
package top.demo.test.spring2;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String argv[]) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext2.xml");
Water cola=(Water) ctx.getBean("cola");
System.out.println(cola);
}
}