0xCAFEBABE

talk is cheap show me the code

0%

spring扩展

All of these flavors come in through extensions(such as XmlBeanDefinitionReader and AutowiredAnnotationBeanPostProcessor) and operate on shared BeanDefinition objects as a core metadata representation. This is the essence of what makes Spring’s container so flexible and extensible. —— 摘自spring官方文档

spring 通过一系列的扩展机制 使得ioc容器变得如此灵活

定制Bean的行为

sprinig通过一系列的接口 来定制 bean的自然行为

生命周期回调

spring 提供了两种ban声明周期回调方法 分别是 初始化(init) 和 销毁(destroy) 对应bean的创建及销毁过程

在IOC容器并给bean的所有属性附上初值时 回调init

在IOC容器销毁时 回调 destroy

InitializingBean / DisposableBean

接口方式的回调

1
2
3
4
5
6
7
8
9
10
public class BeanWithLifecycle implements InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean::afterPropertiesSet......");
}
@Override
public void destroy() throws Exception {
System.out.println("DisposableBean::destroy");
}
}

PostConstruct / PreDestroy

注解方式回调

1
2
3
4
5
6
7
8
@PostConstruct
public void postConstruct(){
System.out.println("PostConstruct.......");
}
@PreDestroy
public void preDestroy(){
System.out.println("PreDestroy..........");
}

bean定义

在bean定义时指定 生命周期回调

1
2
3
4
@Bean(initMethod="initMethod", destroyMethod = "destroyMethod")
BeanWithLifecycle bean(){
return new BeanWithLifecycle();
}

回调顺序

当存在多个声明周期回调时 init方法只会回调一次

按以下顺序进行回调

  • 初始化回调
    1. @PostConstruct
    2. InitializingBean
    3. 自定义init方法
  • 销毁时回调
    1. PreDestroy
    2. DisposableBean
    3. 自定义destroy方法

Aware

spring 提供了一系列的XxxAware接口 回调 可让bean在 在初始化过程中 获取spring底层组件

  • ApplicationContextAware 获取IOC容器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public class BeanWithAware implements ApplicationContextAware {
    private ApplicationContext applicationContext;
    public ApplicationContext getApplicationContext(){
    return applicationContext;
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
    }
    }
  • BeanNameAware 获取bean名称

    1
    2
    3
    4
    5
    6
    public class BeanWithAware implements BeanNameAware {
    @Override
    public void setBeanName(String name) {
    System.out.println("beanName:"+name);
    }
    }

其他的aware

名称 功能
ApplicationEventPublisherAware 获取事件发布器
BeanClassLoaderAware 获取类加载器
BeanFactoryAware 获取bean工厂
BootstrapContextAware 获取ioc容器所在的启动上下文
LoadTimeWeaverAware 获取织入器(AOP)
MessageSourceAware 获取消息源
NotificationPublisherAware spring jmx 通知发布器
ResourceLoaderAware 获取资源加载器
ServletConfigAware 获取servlet 配置 (WEB)
ServletContextAware 获取SevrletContext(WEB)

容器扩展

spring提供了一系列接口以实现对ioc容器的扩展

实现了BeanPostProcessor接口的bean会提前实例化

BeanPostProcessor

bean后置处理器 包含两个回调 postProcessBeforeInitializationpostProcessAfterInitialization 分别在bean初始化之前(bean的init生命周期回调) 和之后调用

可对bean进行个性化定制 ( Spring AOP代理的实现方式)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if(bean instanceof BeanWithLifecycle){
System.out.println("MyBeanPostProcessor::postProcessAfterInitialization......");
BeanWithLifecycle beanWithLifecycle = (BeanWithLifecycle) bean;
System.out.println(beanWithLifecycle.getName());
}

return null;
}

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(bean instanceof BeanWithLifecycle){
System.out.println("MyBeanPostProcessor::postProcessBeforeInitialization......");
BeanWithLifecycle beanWithLifecycle = (BeanWithLifecycle) bean;
System.out.println(beanWithLifecycle.getName());
beanWithLifecycle.setName("blabla");
}
return null;
}

MergedBeanDefinitionPostProcessor

合并BeanDifinition后置处理器

同于后置处理合并的bean定义(原始bean定义的副本)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Component
public class MyMergedBeanDefinitionPostProcessor implements MergedBeanDefinitionPostProcessor {
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {

System.out.println("MyMergedBeanDefinitionPostProcessor::postProcessMergedBeanDefinition");
System.out.println("beanDefinition:"+beanDefinition.toString());
System.out.println("beanType:"+beanType);
System.out.println("beanName:"+beanName);
beanDefinition.setBeanClass(beanType);
System.out.println(beanDefinition.getBeanClass());
}

@Override
public void resetBeanDefinition(String beanName) {

}
}

BeanFactoryPostProcessor

与BeanPostProcessor类似 不同的是 BeanFactoryPostProcessor 可通过BeanFactory操作bean定义信息

1
2
3
4
5
6
public class MyBeanFactoryProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("MyBeanFactoryProcessor#postProcessBeanFactory........");
}
}

BeanDefinitionRegistryPostProcessor

BeanDefinition注册后置处理器 可用于注册bean定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class MyBeanDefinitionPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
System.out.println("MyBeanDefinitionPostProcessor::postProcessBeanDefinitionRegistry");

RootBeanDefinition definition = new RootBeanDefinition();

definition.setBeanClass(String.class);
ConstructorArgumentValues argumentValues = new ConstructorArgumentValues();

argumentValues.addIndexedArgumentValue(0, "Hello");

definition.setConstructorArgumentValues(argumentValues);
registry.registerBeanDefinition("myBean", definition);
}

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}

事件机制

spring 提供了事件发布 监听机制

事件通过ApplicationEventPublisher 发布 (ApplicationEventPublisherAware)

Event / Listener

Event 表示事件 spring 提供了一些标准事件 详见文档

Listener表示监听器

  • Event

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public class MyApplicationEvent extends ApplicationEvent {
    private String message;
    public MyApplicationEvent(Object source) {
    super(source);
    this.message = source.toString();
    }
    public String getMessage() {
    return message;
    }
    }
  • Listener

    1
    2
    3
    4
    5
    6
    public class MyApplicationEventListener implements ApplicationListener<MyApplicationEvent> {
    @Override
    public void onApplicationEvent(MyApplicationEvent event) {
    System.out.println("message:"+event.getMessage());
    }
    }
  • publisher

    1
    2
    3
    4
    5
    6
    7
    public class MyEventBean implements ApplicationEventPublisherAware {
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
    // 阻塞 直到有监听器处理事件
    applicationEventPublisher.publishEvent(new MyApplicationEvent("Hello I'm fine"));
    }
    }

@EventListener

自Spring4.2开始提供基于注解的事件监听

1
2
3
4
5
@EventListener({MyApplicationEvent.class})
@Async // 开启异步模式
public void receive(){
System.out.println("received message..................................................");
}