Spring或者Springboot實現多例
概述
通過Spring管理的類,預設是單例模式,但是如果有的類需要使用獨立的屬性,則需要配置為多例模式的. 但是多例模式不僅僅只是加一個宣告,使用@Autowired進行注入,可能並不會是你想要的結果.因為多例模式的類是需要單獨呼叫的.
不搞清楚原理直接測試:
需要多例的類上加上註解@Scope(“prototype”)
@Component @Scope("prototype") public class ExampleService{ public void test(){ System.out.println("test,current bean is" + this); } }
引用直接使用@Autowired
@Controller
public class ExampleService{
@Autowired
private ExampleService exampleService;
@RequestMapping("test")
public void test(){
exampleService.test();
}
}
結果: 每個request過來的時候,exampleService例項均為同一個例項.
解決辦法:
不使用@Autowired
@Controller public class ExampleService{ @Autowired private org.springframework.beans.factory.BeanFactory beanFactory; @RequestMapping("test") public void test(){ ExampleService exampleService = beanFactory.getBean(ExampleService.class); exampleService.test(); } }
官方文件說明
4.5.3 Singleton beans with prototype-bean dependencies When you use singleton-scoped beans with dependencies on prototype beans, be aware that dependencies are resolved at instantiation time. Thus if you dependency-inject a prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-scoped bean. However, suppose you want the singleton-scoped bean to acquire a new instance of the prototype-scoped bean repeatedly at runtime. You cannot dependency-inject a prototype-scoped bean into your singleton bean, because that injection occurs only once, when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies. If you need a new instance of a prototype bean at runtime more than once, see Section 4.4.6, “Method injection”
《參考: