Java 如何使用@Autowired注解自動注入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;}
測試類
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,無法@Autowired自動注入bean的問題
要在配置類上加上@ComponentScan
同時在RootConfigure和ServletConfig兩個類上scan的對象是不同的
ServletConfig是用來注冊DispatcherServlet的,它只是用來掃描controller層的
RootConfigure用來注冊ContextLoaderListener,他掃描的范圍是除了controller以外的bean,例如dao,service,bean實(shí)體。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. HTML DOM setInterval和clearInterval方法案例詳解2. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案3. 使用css實(shí)現(xiàn)全兼容tooltip提示框4. css代碼優(yōu)化的12個技巧5. WML語言的基本情況6. css進(jìn)階學(xué)習(xí) 選擇符7. 告別AJAX實(shí)現(xiàn)無刷新提交表單8. 使用純HTML的通用數(shù)據(jù)管理和服務(wù)9. CSS hack用法案例詳解10. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)
