0
点赞
收藏
分享

微信扫一扫

Spring基础(六):Bean自动装配


Spring基础(六):Bean自动装配_spring

文章目录

​​Bean自动装配​​

​​一、准备实体类​​

​​二、配置文件​​

​​三、测试代码​​

Bean自动装配

通过property标签可以手动指定给属性进行注入

我们也可以通过自动转配,完成属性的自动注入,就是自动装配,可以简化DI的配置

一、准备实体类

package com.lanson.bean;
/**
* @Author: lansonli
* @Description: MircoMessage:Mark_7001
*/
public class Dept {
}

package com.lanson.bean;
/**
* @Author: lansonli
* @Description: MircoMessage:Mark_7001
*/
public class Emp {
private Dept dept;
@Override
public String toString() {
return "Emp{" +
"dept=" + dept +
'}';
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
public Emp() {
}
public Emp(Dept dept) {
this.dept = dept;
}
}

二、配置文件

<?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dept" class="com.lanson.bean.Dept"></bean>
<!--
autowire 属性控制自动将容器中的对象注入到当前对象的属性上
byName 根据目标id值和属性值注入,要保证当前对象的属性值和目标对象的id值一致
byType 根据类型注入,要保证相同类型的目标对象在容器中只有一个实例
-->
<bean id="emp" class="com.lanson.bean.Emp" autowire="byName"></bean>
</beans>

三、测试代码

package com.lanson.test;
import com.lanson.bean.Emp;
import com.lanson.bean.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @Author: lansonli
* @Description: MircoMessage:Mark_7001
*/
public class Test2 {
@Test
public void testGetBean(){
ClassPathXmlApplicationContext context =new ClassPathXmlApplicationContext("applicationContext2.xml");
Emp emp = context.getBean("emp", Emp.class);
System.out.println(emp);
}
}

  • 📢欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正!
  • 📢本文由 Lansonli 原创
  • 📢停下休息的时候不要忘了别人还在奔跑,希望大家抓紧时间学习,全力奔赴更美好的生活✨
举报

相关推荐

0 条评论