Spring4---自动装配

何为自动装配?

  • 之前使用Spring的配置文件为java程序类配置Bean,并为java程序类中的属性赋值.
  • 而如果java类中拥有其他类的关联属性,例如一个自定义的关联属性Student,这样的操作都是通过"ref"手工的方式指定赋值的.而自动装配的目的就是由IOC容器为Bean属性自动赋值.
  • 普通配置:“p:student-ref=student1”
  • student1为bean的id值
 <bean id="person7" class="mao.shu.spring.Person"
       p:id="123"
       p:name="p命名空间测试"
       p:balance="500"
       p:student-ref="student1">
 </bean>

在这里插入图片描述

自动装配示例

  • 现在有三个java类
    1. Employee
    2. Department
    3. Salary
  • 现在Employee类中包含一个Department属性和一个Salary属性
public class Employee {
    private Integer id;
    private String name;
    private Integer age;
    private String job;
    
    private Department dept;//描述部门
    private Salary salary;//描述工资
//getter和setter方法
//toString方法
}
  • Department类
public class Department {
    private Integer deptno;
    private String dname;
    private String loc;
}
  • Salary类
public class Salary {
    private Integer sid;
    private Double baseSalary;
}
  • 编写autowrite.xml配置文件文件
<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--配置Salary类实例化对象-->
    <bean id="salary" class="mao.shu.spring.autowrite.Salary"
          p:sid="1"
          p:baseSalary="5000.5">
    </bean>

    <!--配置Department类实例化对象-->
    <bean id="department" class="mao.shu.spring.autowrite.Department"
          p:deptno="1290"
          p:dname="软件开发部"
          p:loc="北京">
    </bean>

    <!--配置Employee类实例化对象-->
    <bean id="employee" class="mao.shu.spring.autowrite.Employee"
          p:id="9527"
          p:name="xiemaoshu"
          p:age="22"
          p:job="程序员"
          autowire="byName">

    </bean>

</beans>
  • 测试
package mao.shu.spring.autowrite;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class EmployeeTest {
    private ApplicationContext app;

   @Before
    public void bbefore(){
       this.app = new ClassPathXmlApplicationContext("mao/shu/spring/autowrite/autowrite.xml");
   }

   @Test
    public void testGet(){
       Employee employee = (Employee) this.app.getBean("employee");
       System.out.println(employee);
   }
}


  • 输出结果

在这里插入图片描述

自动装配的缺点

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值