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;
}
測試類
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自動(dòng)注入bean的問題
要在配置類上加上@ComponentScan
同時(shí)在RootConfigure和ServletConfig兩個(gè)類上scan的對(duì)象是不同的
ServletConfig是用來注冊DispatcherServlet的,它只是用來掃描controller層的
RootConfigure用來注冊ContextLoaderListener,他掃描的范圍是除了controller以外的bean,例如dao,service,bean實(shí)體。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot+Thymeleaf靜態(tài)資源的映射規(guī)則說明
這篇文章主要介紹了SpringBoot+Thymeleaf靜態(tài)資源的映射規(guī)則說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
使用MapStruct進(jìn)行Java Bean映射的方式
MapStruct是一個(gè)用于JavaBean映射的注解處理器,它通過注解生成類型安全且性能優(yōu)異的映射代碼,避免手動(dòng)編寫重復(fù)的樣板代碼,主要特性包括類型安全、高性能、簡潔和可定制性,使用步驟包括定義映射接口、創(chuàng)建源類和目標(biāo)類、生成映射代碼并調(diào)用映射方法2025-02-02
Java concurrency之非公平鎖_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
本篇文章主要介紹了Java concurrency之非公平鎖,詳細(xì)的介紹了獲取和釋放非公平鎖,有興趣的同學(xué)可以了解一下2017-06-06
SpringBoot整合RocketMQ批量發(fā)送消息的實(shí)現(xiàn)代碼
這篇文章主要介紹了SpringBoot整合RocketMQ批量發(fā)送消息的實(shí)現(xiàn),文中通過代碼示例講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-04-04
SpringBoot實(shí)現(xiàn)任意位置獲取HttpServletRequest對(duì)象
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)任意位置獲取HttpServletRequest對(duì)象,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11

