# Méthodes pratiques et points de connaissances dans le développement Spring

Méthodes pratiques et points de connaissances dans le développement Spring

Initialisation du bean

Implémenter l'interface InitializingBean

  • InitializingBeanL'interface se trouve dans le package org.springframework.beans.factory. Cette méthode n'est officiellement pas recommandée et la couche framework utilise cette méthode.
@Configuration
public class PeopleBean implements InitializingBean {
    
    

    private static final Logger logger =  LoggerFactory.getLogger(PeopleBean.class);

    private int id;

    private String name;

    @Bean
    public PeopleBean peopleBeanInit(){
    
    
        PeopleBean peopleBeanInit = new PeopleBean();
        peopleBeanInit.setId(this.id);
        peopleBeanInit.setName(this.name);
        return peopleBeanInit;
    }

	// 对象属性赋值
    @Override
    public void afterPropertiesSet() throws Exception {
    
    
        logger.info("=====> 我要对peoplebean 进行初始化!");
        this.id = 100;
        this.name = "李四";
    }
}

Utilisation de l'annotation @PostConstruct

@Configuration
public class PeopleOneBeanInit {
    
    

    private int id;

    private String name;

    @Bean
    public PeopleOneBeanInit peopleOneBean(){
    
    
        PeopleOneBeanInit peopleOneBean = new PeopleOneBeanInit();
        peopleOneBean.setId(this.id);
        peopleOneBean.setName(this.name);
        return peopleOneBean;
    }

	// 使用这个注解可以在这进行对该类属性初始化操作。
    @PostConstruct
    public void init(){
    
    
        this.id = 1001;
        this.name = "测试张三";
    }
}

Méthode de configuration Spring xml

<bean id="helloWorld" class="com.li.entity.HelloWorld" scope="singleton" init-method="init" destroy-method="destroy">
</bean>
public class HelloWorld {
    
    
   public void init() {
    
    
      // 在这里可以对对象属性进行初始化
   }
}
  • Méthode d'annotation
@Configuration
public class PeopleTwoConfig {
    
    

    /**
     * 相当与xml方式配置中的init-method
     * @return
     */
    @Bean(initMethod = "init")
    public PeopleTwoBeanInit peopleTwoBeanInit(){
    
    
        return new PeopleTwoBeanInit();
    }

}

public class PeopleTwoBeanInit {
    
    
    public void init(){
    
    
        this.id = 1005;
        this.name = "李四测试1";
    }
}

Interface BeanPostProcessor

Implémenter l'interface, la réécriture postProcessBeforeInitialization () , postProcessAfterInitialization () , dans le processus de réécriture peut être obtenu Bean propriétés des opérations connexes Bean.

Modifier les informations d'attribut du Bean

@Component
public class UserBeanPostProcessor implements BeanPostProcessor {
    
    

    private static final Logger logger = Logger.getLogger(String.valueOf(UserBeanPostProcessor.class));

	// 在这里可以拿到bean的相关信息,进行相关操作
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    
    
        final String name = "myUser";
        if(name.equals(beanName)){
    
    
            User user = (User) bean;
            user.setName("李四");
            user.setDate(new Date());
            logger.info("=====> postProcessBeforeInitialization():"+ JSONObject.toJSONString(user));
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    
    
        return bean;
    }
}

Obtenir BeanFactory

Conscient au printemps

La classe Aware sert principalement à aider Spring à accéder aux données du conteneur.Dans la méthode d'implémentation de la réécriture de cette classe, vous pouvez obtenir les informations des composants associés, afin de pouvoir les développer en conséquence.

Classes d'implémentation Aware couramment utilisées
  • BeanFactoryAware: Récupérez le conteneur BeanFactory
  • BeanNameAware: Obtenez le nom du haricot
  • ApplicationContextAware: Obtenez ApplicationContext
Obtenez BeanFactory

Implémentez BeanFactoryAware et récupérez les composants Spring appropriés dans setXXX ().

@Component
public class GetBeanFactory implements BeanFactoryAware {
    
    

    private static final Logger logger = LoggerFactory.getLogger(GetBeanFactory.class);

    private BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
    
    
        this.beanFactory = beanFactory;
        MyBeans bean = beanFactory.getBean(MyBeans.class);
        logger.info("-----> 获得当前的BeanFactory "+ beanFactory);
    }

}
Implémentez l'interface ApplicationContextAware et obtenez le ApplicationContext actuel
@Component
public class SpringContextUtils  implements ApplicationContextAware {
    
    

    private static ApplicationContext applicationContext = null;

    private static final Logger logger = LoggerFactory.getLogger(SpringContextUtils.class);

    // 获得重写set()方法获得当前的applicationContext
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    
    
        if(Objects.isNull(SpringContextUtils.applicationContext)){
    
    
            logger.info("=====>ApplicationUtils初始化...");
            SpringContextUtils.applicationContext = applicationContext;
        }
        if(Objects.nonNull(SpringContextUtils.applicationContext)){
    
    
            logger.info("=====>ApplicationUtils初始化成功!");
        }
    }

    /**
     * 获得当前的ApplicationContext
     *
     * @author LiDong
     * @date 2020/11/20
     * @param '[]'
     * @return org.springframework.context.ApplicationContext
     */
    public static ApplicationContext getApplicationContext(){
    
    
        return applicationContext;
    }

    /**
     * 根据名称拿到Bean
     *
     * @author LiDong
     * @date 2020/11/20
     * @param '[name]'
     * @return java.lang.Object
     */
    public static Object getBean(String name){
    
    
        return getApplicationContext().getBean(name);
    }

    /**
     * 从ApplicationContext中获得Bean并且转型
     *
     * @author LiDong
     * @date 2020/11/20
     * @param '[tClass]'
     * @return T
     */
    public static <T> T getBean(Class<T> tClass){
    
    
        return getApplicationContext().getBean(tClass);
    }

}

Méthodes impliquées dans le cycle de vie du haricot

Méthode propre à Bean (Bean actuel)

Constructeur, getter, setter et méthodes spécifiées par init-method et destruction-method, etc.

Méthodes de cycle de vie au niveau du haricot (Bean actuel)

La classe Bean implémente directement les méthodes de l'interface, telles que BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean et d'autres méthodes. Ces méthodes ne sont efficaces que pour le Bean actuel.

Approche au niveau du conteneur

Par exemple, la méthode d'interface BeanPostProcessor, la classe d'implémentation de l'interface est indépendante du bean et sera enregistrée dans le conteneur Spring. Lorsque le conteneur Spring crée un Bean, ces post-processeurs prendront effet.

Approche post-processeur d'usine

Y compris AspectJWeavingEnabler, CustomAutowireConfigurer, ConfigurationClassPostProcessor, etc. Ce sont les BeanFactoryPostProcessors qui ont été implémentés dans le framework Spring pour implémenter certaines fonctions spécifiques.


Cycle de vie de Bean

  • Instanciation: Pour le conteneur BeanFactory, lorsque le Bean demandé n'est pas initialisé, le conteneur appellera createBean pour l'instanciation. Pour le conteneur ApplicationContext, lorsque le conteneur est démarré, tous les beans sont instanciés en obtenant les informations dans l'objet BeanDefinition.

  • Renseignez les propriétés du haricot

  • Appel set () de BeanNameAware

  • Appel set () de BeanFactoryAware

  • Appel set () de ApplicationContextAware

  • Appelez la méthode de pré-initialisation de BeanPost-Processor

  • Appelez afterPropertiesSet () d'InitializingBean

  • Appeler la méthode d'initialisation personnalisée

  • Appelez la méthode de post-initialisation de BeanPost-Processor

  • Le haricot peut être utilisé

Démo
  • StudentBean.java
@Configuration
public class StudentBean {
    
    

    private static final Logger logger = LoggerFactory.getLogger(StudentBean.class);

    @Bean(name = "studentOne")
    public Student getStudentOne(){
    
    
        logger.info("=====> 使用构造函数初始化Bean...");
        return new Student(1001,"张三");
    }

    @Bean(name = "studentTwo")
    public Student getStudentTwo(){
    
    
        logger.info("=====> 使用setter()初始化Bean...");
        Student student = new Student();
        student.setSno(1002);
        student.setName("李四");
        return student;
    }

    @Bean(name = "studentThree",initMethod = "initStudentOne")
    public Student getStudentThree(){
    
    
        return new Student();
    }

}
  • Student.java
@Component
public class Student implements InitializingBean, BeanNameAware, DisposableBean, ApplicationContextAware {
    
    

    private static final Logger logger = LoggerFactory.getLogger(Student.class);

    /**
     * 学生编号
     */
    private int sno;

    /**
     * 学生姓名
     */
    private String name;


    public Student(int sno, String name) {
    
    
        this.sno = sno;
        this.name = name;
        logger.info("----------> 调用有参构造函数...");
    }

    public Student() {
    
    
        logger.info("----------> 调用无参构造函数...");
    }

    /**
     * 重写 BeanNameAware 的set()
     * @param s
     */
    @Override
    public void setBeanName(String s) {
    
    
        logger.info("----------> 调用setBeanName()... "+s+" 当前的Bean信息为:"+this.sno+" " +this.name);
    }

    /**
     * 重写 DisposableBean 的方法
     * @throws Exception
     */
    @Override
    public void destroy() throws Exception {
    
    
        logger.info("---------->  调用 destroy()...当前的Bean信息为:"+this.sno+" " +this.name);
    }

    /**
     * 重写 InitializingBean 的方法
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
    
    
        logger.info("---------->  调用 afterPropertiesSet()...当前的Bean信息为:"+this.sno+" " +this.name);
    }

    /**
     * 重写 ApplicationContextAware 的set()
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    
    
        logger.info("---------->  调用 setApplicationContext()..."+applicationContext);
    }

    public int getSno() {
    
    
        return sno;
    }

    public void setSno(int sno) {
    
    
        this.sno = sno;
    }

    public String getName() {
    
    
        return name;
    }

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

    public void initStudentOne(){
    
    
        this.sno = 1003;
        this.name = "王五";
        logger.info("---------->  调用 initStudentOne()...当前的Bean信息为:"+this.sno+" " +this.name);
    }
}

Je suppose que tu aimes

Origine blog.csdn.net/qq_37248504/article/details/113896952
conseillé
Classement