@Scope("singleton") 唯一bean实例,Spring中的bean默认都是单例的。
@Scope("prototype")每次请求都会创建一个新的bean实例(多例)。
@Scope("request")每一次http请求都会产生一个新的bean,只在http request内有效。
@Scope("session")每一次http请求都会产生一个新的bean,只在http session内有效。
controller层测试代码
import com.example.test2.scope.service.ScopeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/scope")
public class ScopeController {
int i = 0;
@Autowired
private ScopeService scopeService;
@RequestMapping("/test")
/**
* 测试springboot bean的作用域
*/
private void scopeTest(){
System.out.println("controller:"+i++);
scopeService.scopeTest();
}
}
service层的测试代码
package com.example.test2.scope.service;
import org.springframework.stereotype.Service;
@Service
public class ScopeService {
int i = 0;
/**
* springboot bean作用域测试方法
*/
public void scopeTest(){
System.out.println("service:"+i++);
}
}
1.都不加@Scope测试结果:
controller:0
service:0
controller:1
service:1
controller:2
service:2
controller:3
service:3
结论:controller层是单例的bean
service层是单例的bean
2.controller层加@Scope("prototype"),service层不加测试结果
controller:0
service:0
controller:0
service:1
controller:0
service:2
controller:0
service:3
结论:controller层是多例的bean
service层是单例的bean
3.service层加@Scope("prototype"),controller层不加测试结果
controller:0
service:0
controller:1
service:1
controller:2
service:2
controller:3
service:3
结论:controller层是单例的bean
service层是单例的bean(相当于添加的注解未生效)
4. controller层和service层都加@Scope("prototype")测试结果
controller:0
service:0
controller:0
service:0
controller:0
service:0
controller:0
service:0
结论:controller层是多例的bean
service层是多例的bean