問題描述:
最近在做一個功能時,要用到dubbo的filter。於是在實現接口
com.alibaba.dubbo.rpc.Filter後,按照正常思路添加了屬性,代碼如下:
@Activate(group = {Constants.PROVIDER})
public class CatFilterImpl implements Filter {
@Autowired
private ServClientService scService;
.....
}
在invoke方法裏使用到該scService時,卻發現爲NULL,導致本人驚愕。作爲一個新人,在公司裏又只有本人在弄這dubbo。又。。。省去。。
所以是不可能有那麼多時間瞭解dubbo內部,只能找一個土辦法。見笑。
(2017/10/13 發現用Dubbo提供的ServiceBean可獲取dubbobean,因爲該類已經實現了ApplicationContextAware,所以以下做法不用了)
本bo在這裏爲了獲取scService對象。新建一個類,並使之繼承ApplicationContextAware
本代碼取自網絡, 代碼作者忘記了。。。見諒。
@Controller
public class SpringContextHolder implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
checkApplicationContext();
return applicationContext;
}
@SuppressWarnings("unchecked")
public static Object getBean(String name) {
checkApplicationContext();
return applicationContext.getBean(name);
}
@SuppressWarnings("unchecked")
public static T getBean(Class clazz) {
checkApplicationContext();
Map beanMaps = applicationContext.getBeansOfType(clazz);
if (beanMaps!=null && !beanMaps.isEmpty()) {
return (T) beanMaps.values().iterator().next();
} else{
return null;
}
}
private static void checkApplicationContext() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext未注入,請在applicationContext.xml中定義SpringContextHolder");
}
}
}
在這代碼裏,本bo添加了@controller註解,是爲了不用寫配置文件bean。
要注意這裏只能用controller,不能改爲@Service或@Component。改了後果爲applicationContext 將爲空(我也不知道爲什麼只能controller,我一次次試出來的,心疼自己)
若是要寫配置文件bean的話,這個bean也只能寫在controller註解掃描之後纔可。當然這些是爲了讓spring發現ApplicationContextAware有實現類。但是在實際過程中,本bo發現還是不行。苦思不得,窮舉法。
在大量的實驗後,發現只要在控制層的類裏面添加
@Autowired
private SpringContextHolder sh;
就可以使得SpringContextHolder 被spring發現,也就是可以在別的地方使用該類獲取bean對象。
但是由此有引發一個問題,總不能讓他人想用我的filter就得在他人的代碼裏添加這兩行吧於是,本bo自己又新建了一個類
@Controller
@RequestMapping("fff")
public class Centre {
@Autowired
private SpringContextHolder sh;
@RequestMapping("/i")
@ResponseBody
public Object index() throws Exception{
return null;
}
}
好了這樣就不需要麻煩他人了。
總結:本來只是想拿個對象,卻額外的建了兩個類。說明實力太弱。。
若是有哪隻猿在這個有方便的做法,請告知,感激不盡!