我正在学习在Spring框架中注入的bean的范围依赖性。我正在学习解决网站的范围狭窄的Bean依赖性。但是我看不到网站中说明的分辨率。我尝试使用将ApplicationContext bean注入MySingletonBean的方法来获取MyPrototypeBean的实例。但是,我看不出bean创建过程有什么区别。
@SpringBootApplication
@ComponentScan("com.learning.spring.basics.scope.proxy")
public class SpringScopeProxyApplication {
public static void main(String...strings) throws InterruptedException {
ApplicationContext ctx = SpringApplication.run(SpringScopeProxyApplication.class, strings);
SingletonBean bean1=ctx.getBean(SingletonBean.class);
/**
* Singleton bean is wired with a proototypeBean. But since a singleton bean is created only once by the container
* even the autowired proptotyeBean is also created once.
*/
bean1.display();
SingletonBean bean2=ctx.getBean(SingletonBean.class);
bean2.display();
}
}
@Component
public class SingletonBean {
@Autowired
// prototypeBean is of scope prototype injected into singleton bean
private PrototypeBean prototypeBean;
//Fix 1 - Inject ApplicationContext and make the singletonbean applicationcontextaware
@Autowired
private ApplicationContext applicationContext;
public ApplicationContext getApplicationContext() {
return applicationContext;
}
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public PrototypeBean getPrototypeBean() {
return prototypeBean;
}
public void setPrototypeBean(PrototypeBean prototypeBean) {
this.prototypeBean = prototypeBean;
}
// Fix -1 - get the prototypeBean object from applicationContext everytime the method is called
public void display() {
applicationContext.getBean(PrototypeBean.class).showTime();
//prototypeBean.showTime();
}
PrototypeBean
package com.learning.spring.basics.scope.proxy;
import java.time.LocalDateTime;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PrototypeBean {
public void showTime() {
System.out.println("Time is "+LocalDateTime.now().toString());
}
}
预期结果:时间戳记应该不同,因为原型作用域bean应该是新实例
实际结果:时间戳相同,没有区别
答案 0 :(得分:0)
这不是验证SCOPE_PROTOTYPE
bean的正确方法,因为showTime
是一个实例方法,当您通过对象调用它时会执行该实例方法,因此您总是会得到不同的时间戳。但是我不确定您如何获得相同的时间戳,但下面是一个示例
@SpringBootApplication
@ComponentScan("com.learning.spring.basics.scope.proxy")
public class SpringScopeProxyApplication {
public static void main(String...strings) throws InterruptedException {
ApplicationContext ctx = SpringApplication.run(SpringScopeProxyApplication.class, strings);
SingletonBean bean1=ctx.getBean(PrototypeBean.class);
System.out.println(bean1);
SingletonBean bean2=ctx.getBean(PrototypeBean.class);
System.out.println(bean2);
}
}
您将获得两个不同的对象引用
com.learning.spring.basics.scope.proxy.PrototypeBean@48976e6d
com.learning.spring.basics.scope.proxy.PrototypeBean@2a367e93