Scoped Beans as Dependencies

1
2
3
4
5
6
7
8
9
10
11
12
13
@Slf4j
@Component
@RequestScope
public class RequestScopeEntity {

public RequestScopeEntity() {
log.info("############ Create RequestScopeEntity ############");
}

public void doRequestBusiness() {
log.info(Thread.currentThread() + " do current request business");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Slf4j
@RestController
@RequestMapping("scope2")
public class ScopeController2 {

/**
* 实际注入的是 Spring CGLIB 为 RequestScopeEntity 创建的一个代理对象,
* 可以通过打印该对象的 Class 对象的名称来验证,针对每个请求,都会创建一个
* 实际的 RequestScopeEntity 对象,然后将对这个代理对象方法的调用委托给
* 新创建的 RequestScopeEntity 对象
*/
@Autowired
private RequestScopeEntity requestScopeEntity;

@GetMapping("user")
public String userInfo() {
requestScopeEntity.doRequestBusiness();
int scopeEntityHash = requestScopeEntity.hashCode();
log.info("[scope2], requestScopeEntity:[{}], class:[{}]", scopeEntityHash, requestScopeEntity.getClass().getSimpleName());
return scopeEntityHash;
}
}

注入点可以声明为 ObjectFactory<MyTargetBean>, 或者是 Provider<MyTargetBean>Provider<MyTargetBean> (JSR330)

代理模式,装饰器模式,适配器模式