spring ioc控制器总结

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<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生命周期创建后,不受spring容器管理。即<bean id="person" class="com.test.Person" init-method="init" destroy-method="destory" > init方法会调用,但是destory不会调用。prototype范围的bean销毁要交给客户端代码销毁。

自定义bean的属性

  1. Lifecycle Callbacks(生命周期回调)
    初始化回调:1. 实现InitializingBean接口,则会回调afterPropertiesSet()方法
  2. 方法上加注解@PostConstruct。3. 指定init-method方法
    销毁回调:1. 实现DisposableBean接口,则会回调destroy()方法。2. 方法加注解

调用顺序
初始化:

  1. Methods annotated with @PostConstruct

2.afterPropertiesSet() as defined by the InitializingBean callback interface

  1. A custom configured init() method

销毁:Destroy methods are called in the same order:

  1. Methods annotated with @PreDestroy

  2. destroy() as defined by the DisposableBean callback interface

  3. A custom configured destroy() method

Lifecycle接口

。。。。。。

Aware接口,事件回调机制

ApplicationContextAware、ApplicationEventPublisherAware、BeanFactoryAware、ServletContextAware

ApplicationEventPublisherAware实现了该接口的bean,可以获取applicationEventPublisher,用来发布事件。如下代码可以实现事件的监听机制。

  1. 事件信息载体
package com.league.chase.event;

public class User {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  1. 事件
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;
    }
}
  1. 事件发布者
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");
    };
}

  1. 事件监听者
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的扩展点

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.png

AutowiredAnnotationBeanPostProcessor的调用堆栈可以看出,spring的Autowired注解注入是通过BeanPostProcessor实现的。
AutowiredAnnotationBeanPostProcessor调用堆栈.png

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 'spring.cloud.sentinel-com.alibaba.cloud.sentinel.SentinelProperties' of type [com.alibaba.cloud.sentinel.SentinelProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2021-05-11 17:02:54.759 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

。。。。。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,393评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,790评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,391评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,703评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,613评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,003评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,507评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,158评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,300评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,256评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,274评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,984评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,569评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,662评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,899评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,268评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,840评论 2 339

推荐阅读更多精彩内容