最近公司比較忙,一個人需要同時肝多個項目,這次在開發中遇見了一個問題。
由於業務原因,我在開發中使用了抽象工廠設計模式,我手動new了一些對象,但是在執行CRUD操作的時候,發現我注入的數據層訪問對象爲null,既然爲null肯定是註解 沒 生 效(@Autowired) 通常 註解沒有生效只有一個原因 ,該類沒有被spring管理起來,
問題:如何讓spring管理自己new出來的對象呢?
先說下思路,我們的對象之所以能被spring管理起來,是因爲在項目啓動的時候spring掃描了我們的包(package),而雖然我new的對象也在該包中,但是已經由於使用了new關鍵字,導致脫離了spring的管理,所以我們需要手動去獲取Spring的上下文然後使用
下面是解決方案:
package com.xx.xx.xx.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class CustomManageObjUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
}
//獲取applicationContext上下文
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//通過name獲取 Bean.
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
//通過class獲取Bean.
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
//通過name,以及Clazz返回指定的Bean
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
在使用的時候只需要定義一個構造區域
public class xx implements IRegister{
private XXDao xxDao;
// 構造區域 每次new xx()的時候 都會執行
{
xxDao = CustomManageObjUtil.getBean(XXDao.class);
}
@Override
public Integer register(xxPo xx) {
Integer num = xxDao.insert(xx);
return num;
}
}