spring 常用接口和类

spring 常用接口和类

1.InitializingBean

失效此接口的类,在初始化完成之后,会自动调用afterPropertiesSet()方法,但是在init-method方法之后(如果配置)

@Component
public class InitializingBeanTest implements InitializingBean {


    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet 被调用");
    }
}

2.BeanPostProcessor

  bean后置处理器,它是用来拦截所有 bean 的初始化的,在 bean 的初始化之前,和初始化之后做一些事情。这点从 BeanPostProcessor 接口的定义也可以看出来,它里面就两个方法:postProcessBeforeInitialization 和 postProcessAfterInitialization。

  2.1:后置处理器的postProcessorBeforeInitailization方法是在bean实例化,依赖注入之后及自定义初始化方法(例如:配置文件中bean标签添加init-method属性指定Java类中初始化方法、
          @PostConstruct注解指定初始化方法,Java类实现InitailztingBean接口)之前调用
  2.2:后置处理器的postProcessorAfterInitailization方法是在bean实例化、依赖注入及自定义初始化方法之后调用

@Component
public class BeanPostProcessorTest implements BeanPostProcessor {

    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("后置处理器处理bean=【"+beanName+"】开始");
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("后置处理器处理bean=【"+beanName+"】完毕");
        return bean;
    }
}

3.ApplicationContextAware

    当一个类实现了这个接口之后,这个类就可以方便的获得ApplicationContext对象,然后从applicationContext对象中利用getBean()获取容器中的bean

@Component
public class SpringContextHelper implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    public static <T> T getInstance(String beanName, Class<T> beanType) {
        return applicationContext.getBean(beanName, beanType);
    }

    public static <T> T getInstance(Class<T> bean) {
        return applicationContext.getBean(bean);
    }
}

4.BeanFactoryAware

 同ApplicationContextAware对象一样,实现此接口可以获取到BeanFactory对象,然后利用getBean获取我们需要bean


@Service
public class BeanFactoryHelper implements BeanFactoryAware {
    
    private static BeanFactory beanFactory;
 
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
    
    public static Object getBean(String beanName){
 
     if(beanFactory == null){
            throw new NullPointerException("BeanFactory is null!");
        }
 
     return beanFactory.getBean(beanName); 
  } 
}

5.ApplicationRunner

在项目完全启动后,调用实现此接口的方法。

@Component
public class CommonRunner implements ApplicationRunner {


    @Override
    public void run(ApplicationArguments args) throws Exception {

        System.out.println("启动后执行。。。。。");
    }
}

6.@PostConstruct

 在bean初始化之前调用,具体和afterPropertiesSet(),还有init-method调用顺序,可以看下spring的生命周期

 

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » spring 常用接口和类