我能够测试在单例bean中自动装配原型bean只会创建一个原型bean。
为了解决这个问题,我读到可以为原型bean定义AOP作用域代理或使用Spring的查找方法注入。
这是我尝试过的 -
PrototypeBean.java
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.INTERFACES)
public class PrototypeBean implements Prototype {
private String welcomeMessage;
public String getWelcomeMessage() {
return welcomeMessage;
}
public void setWelcomeMessage(final String welcomeMessage) {
this.welcomeMessage = welcomeMessage;
}
}
SingletonBean.java
@Component
public class SingletonBean implements Singleton{
@Autowired private Prototype prototype;
public Prototype getPrototype() {
return prototype;
}
public void greet() {
System.out.println(prototype.getWelcomeMessage());
}
}
测试类
public class AutowiredDependenciesDemo {
@Autowired private Singleton autowiredSingleton;
@Autowired ConfigurableApplicationContext context;
@Test
public void testPrototypeBeanWithAopScopedProxy(){
Assert.assertNotNull(autowiredSingleton);
Prototype prototypeBean = (Prototype) ((SingletonBean) autowiredSingleton).getPrototype();
prototypeBean.setWelcomeMessage("hello world");
autowiredSingleton.greet();
Singleton contextSingleton = (Singleton) context.getBean("singletonBean");
Assert.assertSame(autowiredSingleton, contextSingleton);
Prototype anotherPrototypeBean = (Prototype) ((SingletonBean)contextSingleton).getPrototype();
anotherPrototypeBean.setWelcomeMessage("hello india");
contextSingleton.greet();
autowiredSingleton.greet();
// i expected both the prototype instances to be different. in the debugger, it does show two different 'proxied' instances. however the test fails.
Assert.assertNotSame(prototypeBean, anotherPrototypeBean);
}
我有点不明白这里是否有什么问题?此外,调用greet()方法返回null值。
prototypeBean.setWelcomeMessage("hello world");
和anotherPrototypeBean.setWelcomeMessage("hello india");
。我原本期望这会使Spring创建两个原型bean(根据PrototypeBeanImpl内存地址),但最后的Assert语句并没有确认我的观察结果。 - user3842182