東莞英文建站關(guān)鍵字優(yōu)化
一、使用Spring出錯(cuò)根源
1、隱式規(guī)則的存在
????????你可能忽略了 Sping Boot 中 @SpringBootApplication 是有一個(gè)默認(rèn)的掃描包范圍的。這就是一個(gè)隱私規(guī)則。如果你原本不知道,那么犯錯(cuò)概率還是很高的。類似的案例這里不再贅述。
2、默認(rèn)配置不合理
3、追求奇技淫巧
4、理所當(dāng)然地使用
????????要完整接收到所有的 Header,不能直接使用 Map 而應(yīng)該使用 MultiValueMap。
5、無(wú)關(guān)的依賴變動(dòng)
????????你一定要意識(shí)到,當(dāng)你的代碼不變時(shí),你的依賴變了,行為則可能“異常”了。
6、例如默認(rèn)掃描 Bean 的范圍、自動(dòng)裝配構(gòu)造器等等
7、定義了多個(gè)構(gòu)造器就可能報(bào)錯(cuò),因?yàn)槭褂梅瓷浞绞絹?lái)創(chuàng)建實(shí)例必須要明確使用的是哪一個(gè)構(gòu)造器
8、當(dāng)一個(gè)單例的 Bean,使用 autowired 注解標(biāo)記其屬性時(shí),你一定要注意這個(gè)屬性值會(huì)被固定下來(lái)。
解決方案:
? ? ? ? 解決方案一:自動(dòng)注入 Context
????????即自動(dòng)注入 ApplicationContext,然后定義 getServiceImpl() 方法,在方法中獲取一個(gè)新的 ServiceImpl 類型實(shí)例。修正代碼如下:
@RestController
public class HelloWorldController {@Autowiredprivate ApplicationContext applicationContext;@RequestMapping(path = "hi", method = RequestMethod.GET)public String hi(){return "helloworld, service is : " + getServiceImpl();};public ServiceImpl getServiceImpl(){return applicationContext.getBean(ServiceImpl.class);}}
? ? ? ? 解決方案二:?使用 Lookup 注解
@RestController
public class HelloWorldController {@RequestMapping(path = "hi", method = RequestMethod.GET)public String hi(){return "helloworld, service is : " + getServiceImpl();};@Lookuppublic ServiceImpl getServiceImpl(){return null;} }
二、找不到合適的 Bean,但是原因卻不盡相同。
1、提供的 Bean 過(guò)多又無(wú)法決策選擇誰(shuí);
? ? ? ? 解決方案:精確匹配
@Autowired
DataService oracleDataService;
2、是因?yàn)橹付ǖ拿Q不規(guī)范導(dǎo)致引用的 Bean 找不到。
? ? ? ? 解決方案:定義處顯式指定 Bean 名字,我們可以保持引用代碼不變,而通過(guò)顯式指明 CassandraDataService 的 Bean 名稱為 CassandraDataService 來(lái)糾正這個(gè)問(wèn)題。
@Repository("CassandraDataService")
@Slf4j
public class CassandraDataService implements DataService {//省略實(shí)現(xiàn)
}
3、引用內(nèi)部類的 Bean 遺忘類名
? ? ? ? 解決方案:全部名稱引入
@Autowired
@Qualifier("studentController.InnerClassDataService")
DataService innerClassDataService;
4、 @Value 不僅可以用來(lái)注入 String 類型,也可以注入自定義對(duì)象類型。同時(shí)在注入 String 時(shí),你一定要意識(shí)到它不僅僅可以用來(lái)引用配置文件里配置的值,也可能引用到環(huán)境變量、系統(tǒng)參數(shù)等。
5、我們了解到集合類型的注入支持兩種常見(jiàn)的方式,即上文中我們命名的收集裝配式和直接裝配式。這兩種方式共同裝配一個(gè)屬性時(shí),后者就會(huì)失效。
解決方案:只用一個(gè)
直接裝配
@Bean
public List<Student> students(){Student student1 = createStudent(1, "xie");Student student2 = createStudent(2, "fang");Student student3 = createStudent(3, "liu");Student student4 = createStudent(4, "fu");return Arrays.asList(student1,student2,student3, student4);
}