盡管書(shū)看了厚厚一本万栅,但實(shí)際用起來(lái)未斑,還是經(jīng)常會(huì)碰到一些問(wèn)題。
再次一一進(jìn)行記錄霹肝。
Spring本質(zhì)是一個(gè)容器的管理工具估蹄,所以你如果將要依賴(lài)它的注入功能。你就不能去手動(dòng)new一個(gè)對(duì)象沫换。
例子:
B是一個(gè)bean
class A{
@Autowired
B b;
}
這時(shí)最铁,c想用注入了B的A讯赏,則A也要在C中依靠Spring進(jìn)行注入
把A也設(shè)置成一個(gè)bean
class C{
@Autowired
A a;
}
而不能去new一個(gè)A冷尉,如果是自己new的漱挎,Spring無(wú)法將B注入到A中
很多時(shí)候,我們的job都會(huì)通過(guò)new job的方式進(jìn)行使用雀哨,但如果job中有依賴(lài)自動(dòng)注入磕谅,如何解決呢?
參考文檔:
單例注入到多例是一個(gè)自然的方式雾棺,但多例如何注冊(cè)到單例呢膊夹?注入的過(guò)程是在單例的實(shí)例化過(guò)程中的, 且只有一次
Spring官方文檔給出的是 Method Injection的方式捌浩,例子中的commod放刨,你可以根據(jù)個(gè)人需求,設(shè)置為prototype形式
public class CommandManager implements ApplicationContextAware {
private ApplicationContext applicationContext;
public Object process(Map commandState) {
// grab a new instance of the appropriate Command
Command command = createCommand();
// set the state on the (hopefully brand new) Command instance
command.setState(commandState);
return command.execute();
}
protected Command createCommand() {
// notice the Spring API dependency!
return this.applicationContext.getBean("command", Command.class);
}
public void setApplicationContext(
ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
自動(dòng)注入時(shí)的父類(lèi)和子類(lèi)
實(shí)際碰到的問(wèn)題尸饺,代碼需要用到spring-data 里的RedisTemplate和StringRedisTemplate进统,使用@autowired助币,發(fā)現(xiàn)注入的無(wú)法實(shí)現(xiàn)。
1.@autowired 默認(rèn)注入是 通過(guò)類(lèi)型注入的螟碎,如果要通過(guò)beanID注入眉菱,則需要結(jié)合@Qualifier一起使用。
2.stringRedisTemplate是redisTemplate的子類(lèi)掉分,所以注入會(huì)發(fā)生問(wèn)題倍谜,通過(guò)@Qualifier使用Id注入可解決問(wèn)題
用spring管理的實(shí)例對(duì)象必須包含一個(gè)無(wú)參的構(gòu)造參數(shù)
這個(gè)是改造一些他人不用Spring管理的框架中遇到的,用spring管理的實(shí)例對(duì)象必須包含一個(gè)無(wú)參的構(gòu)造參數(shù)叉抡,否則會(huì)報(bào)錯(cuò)