正如其他 SO 答案所建议的,根据您的需要使用代理模式类型,我仍然很困惑;
@Configuration
@ComponentScan
public class Application
{
public static void main( String[] args )
{
ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
PrototypeBeanFactory factoryBean = context.getBean(PrototypeBeanFactory.class);
System.out.println("Let's start");
SomeInterface b1 = factoryBean.getPrototypeBeanInstance();
SomeInterface b2 = factoryBean.getPrototypeBeanInstance();
System.out.println(b1.hashCode());
System.out.println(b2.hashCode());
b1.sayHello();
b2.sayHello();
b1.sayHello();
b2.sayHello();
}
}
@Component
public class PrototypeBeanFactory {
@Lookup
public PrototypeBean getPrototypeBeanInstance(){
System.out.println("It'll be ignored");
return null;
}
}
@Component
@Scope(value="prototype", proxyMode = ScopedProxyMode.INTERFACES)
public class PrototypeBean {
public PrototypeBean() {
System.out.println("I am created");
}
public void sayHello() {
System.out.println("Hello from " + this.hashCode());
}
}
Output
Let's start
I am created
I am created
1849201180
1691875296
Hello from 1849201180
Hello from 1691875296
Hello from 1849201180
Hello from 1691875296
现在,如果我将代理模式更改为 TARGET_CLASS
Output
Let's start
-721204056
-721204056
I am created
Hello from 172032696
I am created
Hello from 299644693
I am created
Hello from 1771243284
I am created
Hello from 2052256418
为什么在基于类的代理的情况下,它在每次方法调用时创建不同的对象?
@Component
@Scope(value="prototype", proxyMode = ScopedProxyMode.INTERFACES)
public class PrototypeBean { ... }
在您的情况下,这将导致每次调用一个 beangetBean
豆作为你的PrototypeBean
没有实现接口,因此无法创建作用域代理。在您的情况下,您调用查找方法两次,因此您将获得 2 个实例。这实际上是一个人的正常行为prototype
作用域 bean。
Component
@Scope(value="prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class PrototypeBean { ... }
这将导致代理的创建。该代理创建一次,每次调用都会返回getBean
。一旦您在代理上调用方法,它就会根据范围创建一个新方法或重用现有方法。正如您将范围指定为prototype
每个方法调用都会产生一个新对象。
Note:如果您的类将实现一个公开适当方法的接口,则行为不会有任何差异proxyMode = ScopedProxyMode.INTERFACES
and proxyMode = ScopedProxyMode.TARGET_CLASS
在这两种情况下都会创建一个作用域代理。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)