创建PrototypeDemoLM.java文件提供多例
public class PrototypeDemoLM {
}
创建SingletonDemoLM.java文件,将PrototypeDemoLM依赖
public class SingletonDemoLM {
private PrototypeDemoLM prototypeDemoLM;
public PrototypeDemoLM getPrototypeDemoLM() {
return prototypeDemoLM;
}
public void setPrototypeDemoLM(PrototypeDemoLM prototypeDemoLM) {
this.prototypeDemoLM = prototypeDemoLM;
}
}
配置文件
PrototypeDemoLM的bean为多例,SingletonDemoLM 设为单例
<bean id="prototypeDemoLM" class="com.example.demo.demo.PrototypeDemoLM" scope="prototype"></bean>
<bean id="singletonDemoLM" class="com.example.demo.demo.SingletonDemoLM">
<property name="prototypeDemoLM" ref="prototypeDemoLM"></property>
</bean>
使用property标签创建关联
测试类
@Test
void contextLoads() {
System.out.println("spring容器启动中...");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
System.out.println(context.getBean(PrototypeDemoLM.class));
System.out.println(context.getBean(SingletonDemoLM.class));
SingletonDemoLM singletonDemoLM = context.getBean(SingletonDemoLM.class);
System.out.println(singletonDemoLM.getPrototypeDemoLM());
System.out.println("spring容器启动完毕!");
}
控制台打印结果
spring容器启动中...
com.example.demo.demo.PrototypeDemoLM@5d1b9c3d
com.example.demo.demo.SingletonDemoLM$$EnhancerBySpringCGLIB$$508bc356@69e05f61
com.example.demo.demo.PrototypeDemoLM@49a26d19
spring容器启动完毕!
PrototypeDemoLM创建出不同的实例
但是用到spring中的接口ApplicationContextAware,此时对spring的api有耦合的作用,可以使用spring的标签实现样的效果
<bean id="prototypeDemoLM" class="com.example.demo.demo.PrototypeDemoLM" scope="prototype"></bean>
<bean id="singletonDemoLM" class="com.example.demo.demo.SingletonDemoLM">
<lookup-method name="getPrototypeDemoLM" bean="prototypeDemoLM"></lookup-method>
<!-- <property name="prototypeDemoLM" ref="prototypeDemoLM"></property>-->
</bean>
控制台打印结果
spring容器启动中...
com.example.demo.demo.PrototypeDemoLM@bdd2027
com.example.demo.demo.SingletonDemoLM$$EnhancerBySpringCGLIB$$508bc356@31f20c9f
com.example.demo.demo.PrototypeDemoLM@f446158
spring容器启动完毕!
lookup-method:看其名字,就知道意思:方法查找,调用name属性指定的方法的时候,spring会对这个方法进行拦截,然后去容器中查找lookup-method元素中bean属性指定的bean,然后将找到的bean作为方法的返回值返回。