Java 如何使用@Autowired注解自動(dòng)注入bean
annotationWire.xml (一定記得配置context:annotation-config/)
<?xml version='1.0' encoding='UTF-8'?><beans xmlns='http://www.springframework.org/schema/beans' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:context='http://www.springframework.org/schema/context' xmlns:p='http://www.springframework.org/schema/p' xsi:schemaLocation='http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd'> <context:annotation-config/> <bean p:order='202020124546' /> <bean /></beans>
User類
package com.annotationWire.pojo;import lombok.Data;import org.springframework.beans.factory.annotation.Autowired;@Datapublic class User { private String name; @Autowired private Order order;}
Order類
package com.annotationWire.pojo;import lombok.Data;@Datapublic class Order { private String order;}
測(cè)試類
package com.annotationWire;import com.annotationWire.pojo.User;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestAnnotation { @Test public void test(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext('annotationWire.xml');User student = applicationContext.getBean(User.class);System.out.println(student); }}java配置spring,無(wú)法@Autowired自動(dòng)注入bean的問(wèn)題
要在配置類上加上@ComponentScan
同時(shí)在RootConfigure和ServletConfig兩個(gè)類上scan的對(duì)象是不同的
ServletConfig是用來(lái)注冊(cè)DispatcherServlet的,它只是用來(lái)掃描controller層的
RootConfigure用來(lái)注冊(cè)ContextLoaderListener,他掃描的范圍是除了controller以外的bean,例如dao,service,bean實(shí)體。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 基于PHP做個(gè)圖片防盜鏈2. ASP.NET MVC使用Boostrap實(shí)現(xiàn)產(chǎn)品展示、查詢、排序、分頁(yè)3. .NET中實(shí)現(xiàn)對(duì)象數(shù)據(jù)映射示例詳解4. jscript與vbscript 操作XML元素屬性的代碼5. asp.net core 認(rèn)證和授權(quán)實(shí)例詳解6. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)7. XML在語(yǔ)音合成中的應(yīng)用8. 如何使用ASP.NET Core 配置文件9. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)車輛管理系統(tǒng)10. ASP.NET MVC把數(shù)據(jù)庫(kù)中枚舉項(xiàng)的數(shù)字轉(zhuǎn)換成文字
