ApplicationContextAware(org.springframework.context.ApplicationContextAware)

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


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

@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(org.springframework.beans.factory.InitializingBean)

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


import org.springframework.beans.factory.InitializingBean;
 
public class SpringBeanInit implements InitializingBean {
  
 
    private String name;
  
 /** 这里进行优先调用初始化一些参数
 */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("this is bean init,name:"+name); 
    }
  
}