Spring中一些方便的的接口和类

文章目录

  • ApplicationContextAware 接口
  • InitialzingBean接口

ApplicationContextAware 接口

当一个类实现了这个接口之后,这个类就可以方便的获得ApplicationContext对象(spring上下文),Spring发现某个Bean实现了ApplicationContextAware接口,Spring容器会在创建该Bean之后,自动调用该Bean的setApplicationContext(参数)方法,调用该方法时,会将容器本身ApplicationContext对象作为参数传递给该方法。

package com.lyj.demo.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author 凌兮
 * @date 2020/5/18 15:39
 * 全局上下文
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
    public static ApplicationContext getApplicationContext(){
        return context;
    }
    /**
     * 通过name获取 Bean
     * @param name beanName
     * @return Object
     */
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }



    public static <T> T getBean(Class<T> requiredType) throws BeansException{
        return getApplicationContext().getBean(requiredType);
    }
}



InitialzingBean接口

当一个类实现这个接口之后,Spring启动后,初始化Bean时,若该Bean实现InitialzingBean接口,会自动调用afterPropertiesSet()方法,完成一些用户自定义的初始化操作。

使用步骤:
1、编写一个类引用InitializingBean接口,重写其中的afterPropertiesSet方法,在其中写自己的方法

@Data
@Component
public class SpringBeanInit implements InitializingBean {

    private Integer id;

    private String name;

    private Integer age;

    private boolean sex;

    private Student student;

    /** 这里进行优先调用初始化一些参数
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("---------- this is bean init set student data ----------");
        Student student = new Student(1,"name",2,true);
        this.student = student;
    }

    public void testInit(){
        System.out.println("this is bean web.xml init-method invock");
    }
}

2、在任意地方注入bean,都会直接执行重写的afterPropertiesSet方法,不用主动调用

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApplication.class)
public class InitializingBeanTest {

     // 注入bean
    @Autowired
    SpringBeanInit beanInit;
    @Test
    public void test1(){

        System.out.println(JSON.toJSONString(beanInit));
        System.out.println(JSON.toJSONString(beanInit.getStudent()));
    }
}

结果:
在这里插入图片描述

你可能感兴趣的:(Spring,java,spring,java,spring,boot)