Spring中Bean的作用域Scope你知道多少?如何自定义作用域?( 二 )

target = null ;return "success" ;}@Overridepublic void registerDestructionCallback(String name, Runnable callback) {}@Overridepublic Object resolveContextualObject(String key) {return null;}@Overridepublic String getConversationId() {return null;}}注册Scope
@Componentpublic class CustomScopeRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {beanFactory.registerScope("custom", new CustomScope()) ;}@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {}}使用Scope
@Component@Scope("custom")public class ApplyScopeBean {}示例
@RestController@RequestMapping("/refresh")@Scope(value = https://www.isolves.com/it/cxkf/jiagou/2023-09-05/ConfigurableBeanFactory.SCOPE_PROTOTYPE)public class RefreshController implements ApplicationContextAware{@Resourceprivate ApplyScopeBean scopeBean ;@Resourceprivate CustomScope customScope ;@GetMapping("/custom")public String custom() {return scopeBean.getCustom() ;}@GetMapping("/remove") public Object remove() {return customScope.remove("applyScopeBean") ;}}【Spring中Bean的作用域Scope你知道多少?如何自定义作用域?】这里将Controller设置为多例,以便查看效果 。交替执行上面的接口,只要删除了就会创建新的实例 。
3 多例注入如果一个Bean 设置了@Scope(value =https://www.isolves.com/it/cxkf/jiagou/2023-09-05/
ConfigurableBeanFactory.SCOPE_PROTOTYPE) 当这个Bean需要在一个单例Bean中被注入时,需要如下配置才可
@Component@Scope(value = https://www.isolves.com/it/cxkf/jiagou/2023-09-05/ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)public class ApplyScopeBean {}
这样才能正确地注入Bean,否则因为本身使用者是单例的,属性只会被初始化一次 。也可以在每次使用前调用BeanFactory#getBean() 。
完毕!!!




推荐阅读