Springソースラーニング--SpringbootのApplicationContextからBeanを取得

4883 ワード

クラスAが注入できない場合、Springで注入された他のオブジェクトBを使用する必要がある場合、AクラスでBを使用したい場合は、次のようにします.
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

/**
 * Description:  bean  
 * 
 * @author DemoTransfer
 * @date 2018 5 19    1:42:56
 */
public class SpringBeanUtil {

    private static ApplicationContext applicationContext;
    static final private Object lock = new Object();

    /**
     *      
     * 
     * @param applicationContext
     * @throws BeansException
     */
    public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        synchronized (lock) {
            if (SpringBeanUtil.applicationContext == null) {
                SpringBeanUtil.applicationContext = applicationContext;
            }
        }
    }

    /**
     *   applicationContext
     * 
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     *   name   Bean
     * 
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     *   class  Bean
     * 
     * @param clazz
     * @return
     */
    public static  T getBean(Class clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     *   name,  Clazz     Bean
     * 
     * @param name
     * @param clazz
     * @return
     */
    public static  T getBean(String name, Class clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

ApplicationContextの場所の設定
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class WebApplication {

    private static ApplicationContext applicationContext;

    public static void main(String[] args) {
        applicationContext = SpringApplication.run(WebApplication.class, args);
        SpringBeanUtil.setApplicationContext(applicationContext);
    }

}

シーンの操作
UnInstallServiceImpl unInstallServiceImpl = (UnInstallServiceImpl) SpringBeanUtil.getBean("unInstallService");