使用@Autowired注解自动注入bean
程序员文章站
2022-07-03 19:36:48
头部配置
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);
}
}
本文地址:https://blog.csdn.net/weixin_44371237/article/details/111958116
推荐阅读
-
netcore 2.2 使用 Autofac 实现自动注入
-
Spring注解驱动开发第3讲——使用@ComponentScan自动扫描组件并指定扫描规则
-
@Autowired 和 @Resource注解, 一个接口有多个实现类的时候Spring注入遇到的问题
-
荐 Spring-boot-study02-spring.xml配置文件注入组件和@Bean注解注入组件差别
-
@Autowired自动注入失败
-
详解SpringBoot 多线程处理任务 无法@Autowired注入bean问题解决
-
静态方法中直接使用注入的bean对象
-
静态方法中直接使用注入的bean对象
-
使用@Autowired注入map
-
Spring(16)——使用注解进行bean定义