spring bean创建的生命周期

2022-10-25 17:13:47 浏览数 (1)

文章目录
  • spring bean创建的生命周期
    • 1. 生成BeanDefinition
    • 2. 合并BeanDefinition
    • 3. 加载类
    • 4. 实例化前
    • 5. 推断构造方法
    • 6. 实例化
    • 7. BeanDefinition的后置处理
    • 8. 属性填充
    • 9. 执行Aware
    • 10. 初始化前
      • ApplicationContextAwareProcessor主要是执行一些其他的Aware
      • InitDestroyAnnotationBeanPostProcessor
    • 11. 初始化
      • 执行InitializingBean接口中的方法
      • 执行BeanDefinition中所定义的初始化方法
    • 12. 初始化后
    • 实例:

spring bean创建的生命周期

1. 生成BeanDefinition

2. 合并BeanDefinition

3. 加载类

4. 实例化前

5. 推断构造方法

6. 实例化

7. BeanDefinition的后置处理

8. 属性填充

9. 执行Aware

  • BeanNameAware
  • BeanClassLoaderAware
  • BeanFactoryAware

10. 初始化前

ApplicationContextAwareProcessor主要是执行一些其他的Aware
  • EnvironmentAware
  • EmbeddedValueResolverAware
  • ResourceLoaderAware
  • ApplicationEventPublisherAware
  • MessageSourceAware
  • ApplicationContextAware
InitDestroyAnnotationBeanPostProcessor

执行@PostConstruct定义的方法

11. 初始化

执行InitializingBean接口中的方法
执行BeanDefinition中所定义的初始化方法

12. 初始化后

AbstractAutoProxyCreator aop功能实现者

实例:

代码语言:javascript复制
package com.xiepanpan;

import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.function.Supplier;

/**
 * <p>Description: </p>
 * <p>Copyright: Copyright (c)2,020</p>
 * <p>Company: tope</p>
 * <P>Created Date :2021/5/19</P>
 *
 * @author xiepanpan
 * @version 1.0
 */
public class Main {

    public static void main(String[] args) {
  

        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);

        UserServiceInterface userService = applicationContext.getBean("userService", UserServiceInterface.class);

        userService.love();


    }
}
代码语言:javascript复制
package com.xiepanpan;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * <p>Description: </p>
 * <p>Copyright: Copyright (c)2,020</p>
 * <p>Company: tope</p>
 * <P>Created Date :2021/5/21</P>
 *
 * @author xiepanpan
 * @version 1.0
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Xpp {

    String value();
}

XppBeanPostProcessor

代码语言:javascript复制
package com.xiepanpan;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.*;

/**
 * <p>Description: </p>
 * <p>Copyright: Copyright (c)2,020</p>
 * <p>Company: tope</p>
 * <P>Created Date :2021/5/21</P>
 *
 * @author xiepanpan
 * @version 1.0
 */
@Component
public class XppBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if (beanName.equals("userService")) {

            System.out.println("实例化前");
        }
        return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInstantiation(beanClass, beanName);
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if (beanName.equals("userService")) {
            System.out.println("实例化后");
        }
        return InstantiationAwareBeanPostProcessor.super.postProcessAfterInstantiation(bean, beanName);
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("userService")) {

            System.out.println("初始化前");
            for (Method method:bean.getClass().getMethods()) {
                if (method.isAnnotationPresent(PostConstruct.class)) {
                    try {
                        method.invoke(bean);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        for (Field field: clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(Xpp.class)) {
                Xpp xpp = field.getAnnotation(Xpp.class);
                field.setAccessible(true);
                try {
                    field.set(bean,xpp.value());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        if (beanName.equals("userService")) {

            System.out.println("初始化后");
            //在这里进行aop操作
            Object o = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("代理逻辑1");
                    method.invoke(bean,args);
                    System.out.println("代理逻辑2");
                    return null;
                }
            });
            return o;
        }
        return bean;
    }
}

UserServiceInterface

代码语言:javascript复制
package com.xiepanpan;

/**
 * <p>Description: </p>
 * <p>Copyright: Copyright (c)2,020</p>
 * <p>Company: tope</p>
 * <P>Created Date :2021/5/21</P>
 *
 * @author xiepanpan
 * @version 1.0
 */
public interface UserServiceInterface {

    void love();
}

UserService

代码语言:javascript复制
package com.xiepanpan;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * <p>Description: </p>
 * <p>Copyright: Copyright (c)2,020</p>
 * <p>Company: tope</p>
 * <P>Created Date :2021/5/21</P>
 *
 * @author xiepanpan
 * @version 1.0
 */
@Component
public class UserService implements InitializingBean,UserServiceInterface{

    private User user;

    @Autowired
    public void setUser(User user) {
        System.out.println("属性填充 set方法注入");
        this.user = user;
    }

    @Autowired(required = false)
    public UserService(User user) {
        System.out.println("一个参数的构造方法");
    }

    @Autowired(required = false)
    public UserService(User user,User user1) {
        System.out.println("两个参数的构造方法");
    }

    @Xpp("zhijie")
    String name;

    public void test() {
        System.out.println(name);
    }

    /**
     * PostConstruct在构造函数之后执行,init()方法之前执行。
     */
    @PostConstruct
    public void loveZhijie(){
        System.out.println("PostConstruct构造");
    }

    /**
     * 在spring属性注入后调用
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化方法");
    }

    @Override
    public void love() {
        System.out.println("业务逻辑");
    }
}

config类

代码语言:javascript复制
package com.xiepanpan;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

/**
 * <p>Description: </p>
 * <p>Copyright: Copyright (c)2,020</p>
 * <p>Company: tope</p>
 * <P>Created Date :2021/5/19</P>
 *
 * @author xiepanpan
 * @version 1.0
 */
@ComponentScan("com.xiepanpan")
public class Config {

    @Bean
    public User user() {
        return new User();
    }

    @Bean
    public User user2() {
        return new User();
    }
}

User类

代码语言:javascript复制
package com.xiepanpan;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * <p>Description: </p>
 * <p>Copyright: Copyright (c)2,020</p>
 * <p>Company: tope</p>
 * <P>Created Date :2021/5/19</P>
 *
 * @author xiepanpan
 * @version 1.0
 */
public class User {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

运行结果:

代码语言:javascript复制
实例化前
一个参数的构造方法
实例化后
属性填充 set方法注入
初始化前
PostConstruct构造
PostConstruct构造
初始化方法
初始化后
代理逻辑1
业务逻辑
代理逻辑2

0 人点赞