Java 如何使用@Autowired注解自動(dòng)注入bean
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 id="order" class="com.annotationWire.pojo.Order" p:order="202020124546" /> <bean id="user" class="com.annotationWire.pojo.User" /> </beans>
User類
package com.annotationWire.pojo; import lombok.Data; import org.springframework.beans.factory.annotation.Autowired; @Data public class User { private String name; @Autowired private Order order; }
Order類
package com.annotationWire.pojo; import lombok.Data; @Data public 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è)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java與Android使用監(jiān)聽(tīng)者模式示例
這篇文章主要為大家介紹了Java與Android使用監(jiān)聽(tīng)者模式示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08Java使用NIO優(yōu)化IO實(shí)現(xiàn)文件上傳下載功能
IO 是基于流來(lái)讀取的,而NIO則是基于塊讀取,面向流 的 I/O 系統(tǒng)一次一個(gè)字節(jié)地處理數(shù)據(jù),這篇文章主要介紹了Java使用NIO優(yōu)化IO實(shí)現(xiàn)文件上傳下載功能,需要的朋友可以參考下2022-07-07java實(shí)現(xiàn)導(dǎo)出數(shù)據(jù)為zip壓縮文件
這篇文章主要為大家詳細(xì)介紹了java如何實(shí)現(xiàn)導(dǎo)出數(shù)據(jù)為zip壓縮文件,并且解壓后為json文件,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-11-11