1. 程式人生 > >SpringBoot中注入ApplicationContext物件的三種方式

SpringBoot中注入ApplicationContext物件的三種方式

在專案中,我們可能需要手動獲取spring中的bean物件,這時就需要通過 ApplicationContext 去操作一波了!

1、直接注入(Autowired)

@Component
public class User {

    @Autowired
    private ApplicationContext applicationContext;
}

2、構造器方法注入

@Component
public class User{
    private ApplicationContext applicationContext;

    public User
(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } }

3、手動構建類實現介面

/**
 * Spring的ApplicationContext的持有者,可以用靜態方法的方式獲取spring容器中的bean
 *
 * @author yj
 * @date 2018年5月27日 下午6:32:11
 */
@Component
public class SpringContextHolder implements ApplicationContextAware
{
private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextHolder.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext
() { assertApplicationContext(); return applicationContext; } @SuppressWarnings("unchecked") public static <T> T getBean(String beanName) { assertApplicationContext(); return (T) applicationContext.getBean(beanName); } public static <T> T getBean(Class<T> requiredType) { assertApplicationContext(); return applicationContext.getBean(requiredType); } private static void assertApplicationContext() { if (SpringContextHolder.applicationContext == null) { throw new RuntimeException("applicaitonContext屬性為null,請檢查是否注入了SpringContextHolder!"); } } }

注:在使用該類靜態方法時必須保證spring載入順序正確!
可以在使用類上新增 @DependsOn(“springContextHolder”),確保在此之前 SpringContextHolder 類已載入!