bean的作用域
范围 | 描述 |
---|---|
singleton | 单例 |
prototype | 原型 |
request | ApplicationContext |
session | ApplicationContext |
application | ApplicationContext |
websocket | WebSocket |
singleton与prototype都是spring内置的,默认是singleton。prototype是每次获取bean都会创建新的bean. request、session、application都是在web应用中生效。websocket是指在一个websocket链接中生效。
自定义scope,实现org.springframework.beans.factory.config.Scope接口即可。参考org.springframework.context.support.SimpleThreadScope
@Override
public Object get(String name, ObjectFactory> objectFactory) {
Map scope = this.threadScope.get();
Object scopedObject = scope.get(name);
if (scopedObject == null) {
scopedObject = objectFactory.getObject();
scope.put(name, scopedObject);
}
return scopedObject;
}
prototype范围的bean生命周期创建后,不受spring容器管理。即
自定义bean的属性
- Lifecycle Callbacks(生命周期回调)
初始化回调:1. 实现InitializingBean接口,则会回调afterPropertiesSet()方法 - 方法上加注解@PostConstruct。3. 指定init-method方法
销毁回调:1. 实现DisposableBean接口,则会回调destroy()方法。2. 方法加注解
调用顺序:
初始化:
- 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接口,事件回调机制
ApplicationContextAware、ApplicationEventPublisherAware、BeanFactoryAware、ServletContextAware
ApplicationEventPublisherAware实现了该接口的bean,可以获取applicationEventPublisher,用来发布事件。如下代码可以实现事件的监听机制。
- 事件信息载体
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;
}
}
- 事件发布者
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");
};
}
- 事件监听者
package com.league.chase.event;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
@Service
public class RegisterEventListener implements ApplicationListener {
@Override
public void onApplicationEvent(RegisterEvent applicationEvent) {
System.out.println("事件---"+applicationEvent.getSource().getClass().getName());
UserService service = (UserService) applicationEvent.getSource();
service.sayHello();
}
}
spring的扩展点
BeanPostProcessor
在bean创建、实例化之后,初始化调用前后进行一些逻辑的操作,可以修改bean的属性,返回等等。
package org.springframework.beans.factory.config;
import org.springframework.beans.BeansException;
public interface BeanPostProcessor {
//@PostConstruct注解方法、InitializingBean接口的afterPropertiesSet方法、init-method方法**调用之前执行**。
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
//@PostConstruct注解方法、InitializingBean接口的afterPropertiesSet方法、init-method方法**调用之后执行**。
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实现了BeanPostProcessor接口
AutowiredAnnotationBeanPostProcessor的调用堆栈可以看出,spring的Autowired注解注入是通过BeanPostProcessor实现的。
BeanFactoryPostProcessor
在bean实例化之前,对bean的元数据进行逻辑操作处理
PropertySourcesPlaceholderConfigurer对@Value属性进行解析。
下面的demo,模拟PropertySourcesPlaceholderConfigurer,对bean的属性进行注入值。
package com.league.chase.beanFactoryPostProcessor;
import org.springframework.stereotype.Service;
/**
* BeanFactoryPostProcessor实现类
* @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的属性设置值。
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是作用于实例化之前,BeanPostProcessor作用于bean实例化之后,且初始化方法调用之前后。
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的实例化逻辑接口FactoryBean
Environment Abstraction
。。。。。