bean的作用域
范圍 | 描述 |
---|---|
singleton | 單例 |
prototype | 原型 |
request | ApplicationContext |
session | ApplicationContext |
application | ApplicationContext |
websocket | WebSocket |
singleton與prototype都是spring內(nèi)置的赂毯,默認(rèn)是singleton。prototype是每次獲取bean都會創(chuàng)建新的bean. request拣宰、session党涕、application都是在web應(yīng)用中生效。websocket是指在一個(gè)websocket鏈接中生效巡社。
自定義scope,實(shí)現(xiàn)org.springframework.beans.factory.config.Scope接口即可膛堤。參考o(jì)rg.springframework.context.support.SimpleThreadScope
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
Map<String, Object> scope = this.threadScope.get();
Object scopedObject = scope.get(name);
if (scopedObject == null) {
scopedObject = objectFactory.getObject();
scope.put(name, scopedObject);
}
return scopedObject;
}
prototype范圍的bean生命周期創(chuàng)建后,不受spring容器管理晌该。即<bean id="person" class="com.test.Person" init-method="init" destroy-method="destory" > init方法會調(diào)用肥荔,但是destory不會調(diào)用绿渣。prototype范圍的bean銷毀要交給客戶端代碼銷毀。
自定義bean的屬性
- Lifecycle Callbacks(生命周期回調(diào))
初始化回調(diào):1. 實(shí)現(xiàn)InitializingBean接口燕耿,則會回調(diào)afterPropertiesSet()方法 - 方法上加注解@PostConstruct中符。3. 指定init-method方法
銷毀回調(diào):1. 實(shí)現(xiàn)DisposableBean接口,則會回調(diào)destroy()方法誉帅。2. 方法加注解
調(diào)用順序:
初始化:
- Methods annotated with @PostConstruct
2.afterPropertiesSet() as defined by the InitializingBean callback interface
- A custom configured init() method
銷毀:Destroy methods are called in the same order:
Methods annotated with @PreDestroy
destroy() as defined by the DisposableBean callback interface
A custom configured destroy() method
Lifecycle接口
淀散。。蚜锨。档插。。踏志。
Aware接口阀捅,事件回調(diào)機(jī)制
ApplicationContextAware、ApplicationEventPublisherAware针余、BeanFactoryAware、ServletContextAware
ApplicationEventPublisherAware實(shí)現(xiàn)了該接口的bean凄诞,可以獲取applicationEventPublisher圆雁,用來發(fā)布事件。如下代碼可以實(shí)現(xiàn)事件的監(jiān)聽機(jī)制帆谍。
- 事件信息載體
package com.league.chase.event;
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- 事件
package com.league.chase.event;
import org.springframework.context.ApplicationEvent;
public class RegisterEvent extends ApplicationEvent {
/**
* Create a new ApplicationEvent.
*
* @param source the component that published the event (never {@code null})
*/
private User user;
public RegisterEvent(Object source, User user) {
super(source);
this.user = user;
}
public User getUser() {
return user;
}
}
- 事件發(fā)布者
package com.league.chase.event;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
@Service
public class UserService implements ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
public void register(String userName){
applicationEventPublisher.publishEvent(new RegisterEvent(this,new User()));
}
public void sayHello(){
System.out.println("userService sayHello");
};
}
- 事件監(jiān)聽者
package com.league.chase.event;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
@Service
public class RegisterEventListener implements ApplicationListener<RegisterEvent> {
@Override
public void onApplicationEvent(RegisterEvent applicationEvent) {
System.out.println("事件---"+applicationEvent.getSource().getClass().getName());
UserService service = (UserService) applicationEvent.getSource();
service.sayHello();
}
}
spring的擴(kuò)展點(diǎn)
BeanPostProcessor
在bean創(chuàng)建伪朽、實(shí)例化之后,初始化調(diào)用前后進(jìn)行一些邏輯的操作汛蝙,可以修改bean的屬性烈涮,返回等等。
package org.springframework.beans.factory.config;
import org.springframework.beans.BeansException;
public interface BeanPostProcessor {
//@PostConstruct注解方法窖剑、InitializingBean接口的afterPropertiesSet方法坚洽、init-method方法**調(diào)用之前執(zhí)行**。
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
//@PostConstruct注解方法西土、InitializingBean接口的afterPropertiesSet方法讶舰、init-method方法**調(diào)用之后執(zhí)行**。
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
demo如下代碼
package com.league.chase.beanPostProcessor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
@Service
public class BeanPostProcessorService implements InitializingBean {
private int age = 1;
@PostConstruct
public void init(){
System.out.println("BeanPostProcessorService----> init");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("BeanPostProcessorService----> afterPropertiesSet");
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package com.league.chase.beanPostProcessor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(beanName.equals("beanPostProcessorService")){
System.out.println("postProcessBeforeInitialization beanName---->"+beanName);
BeanPostProcessorService newBean = (BeanPostProcessorService) bean;
((BeanPostProcessorService) bean).setAge(2);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if(beanName.equals("beanPostProcessorService")){
System.out.println("postProcessAfterInitialization beanName---->"+beanName);
System.out.println("postProcessAfterInitialization beanName---->"+((BeanPostProcessorService)bean).getAge());
BeanPostProcessorService newBean = new BeanPostProcessorService();
newBean = new BeanPostProcessorService();
newBean.setAge(3);
return newBean;
}
return bean;
}
}
輸出
postProcessBeforeInitialization beanName---->beanPostProcessorService
BeanPostProcessorService----> init
BeanPostProcessorService----> afterPropertiesSet
postProcessAfterInitialization beanName---->beanPostProcessorService
postProcessAfterInitialization beanName---->2
AutowiredAnnotationBeanPostProcessor實(shí)現(xiàn)了BeanPostProcessor接口
AutowiredAnnotationBeanPostProcessor的調(diào)用堆椥枇耍可以看出跳昼,spring的Autowired注解注入是通過BeanPostProcessor實(shí)現(xiàn)的。
BeanFactoryPostProcessor
在bean實(shí)例化之前肋乍,對bean的元數(shù)據(jù)進(jìn)行邏輯操作處理
PropertySourcesPlaceholderConfigurer對@Value屬性進(jìn)行解析鹅颊。
下面的demo,模擬PropertySourcesPlaceholderConfigurer,對bean的屬性進(jìn)行注入值墓造。
package com.league.chase.beanFactoryPostProcessor;
import org.springframework.stereotype.Service;
/**
* BeanFactoryPostProcessor實(shí)現(xiàn)類
* @author chase
*/
@Service
public class BeanFactoryPostProcessorService {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "BeanFactoryPostProcessorService{" +
"name='" + name + '\'' +
'}';
}
}
package com.league.chase.beanFactoryPostProcessor;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.ScannedGenericBeanDefinition;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Service;
/**
* @author chase
*/
@Service
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor, PriorityOrdered {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
//configurableListableBeanFactory可以修改bean的定義堪伍,注冊新的bean等锚烦。
BeanDefinition service = configurableListableBeanFactory.getBeanDefinition("beanFactoryPostProcessorService");
//模擬 PropertySourcesPlaceholderConfigurer向 bean的屬性設(shè)置值。
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("name","zhangsan"));
((ScannedGenericBeanDefinition) service).setPropertyValues(pvs);
System.out.println("MyBeanFactoryPostProcessor postProcessBeanFactory():"+service.getBeanClassName());
}
@Override
public int getOrder() {
return 0;
}
}
package com.league.chase.beanFactoryPostProcessor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyBeanFactoryPostProcessorTest {
@Autowired
private BeanFactoryPostProcessorService service;
@Test
public void postProcessBeanFactoryTest() {
System.out.println("MyBeanFactoryPostProcessorTest---->"+service.getName());
}
}
輸出如下杠娱,從輸出可以看出BeanFactoryPostProcessor是作用于實(shí)例化之前挽牢,BeanPostProcessor作用于bean實(shí)例化之后,且初始化方法調(diào)用之前后摊求。
MyBeanFactoryPostProcessor postProcessBeanFactory():com.league.chase.beanFactoryPostProcessor.BeanFactoryPostProcessorService
2021-05-11 17:02:54.756 INFO 28341 --- [ main] trationDelegateBeanPostProcessorChecker : Bean 'com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration' of type [com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
postProcessBeforeInitialization beanName---->beanPostProcessorService
BeanPostProcessorService----> init
BeanPostProcessorService----> afterPropertiesSet
postProcessAfterInitialization beanName---->beanPostProcessorService
postProcessAfterInitialization beanName---->2
2021-05-11 17:02:56.195 INFO 28341 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-05-11 17:02:56.282 INFO 28341 --- [ main] c.a.c.s.SentinelWebAutoConfiguration : [Sentinel Starter] register SentinelWebInterceptor with urlPatterns: [/**].
2021-05-11 17:02:57.814 INFO 28341 --- [ main] o.s.cloud.commons.util.InetUtils : Cannot determine local hostname
2021-05-11 17:02:57.896 INFO 28341 --- [ main] c.l.c.b.MyBeanFactoryPostProcessorTest : Started MyBeanFactoryPostProcessorTest in 1454.614 seconds (JVM running for 1456.377)
MyBeanFactoryPostProcessorTest---->zhangsan
自定義bean的實(shí)例化邏輯接口FactoryBean
Environment Abstraction
禽拔。。室叉。睹栖。。