Spring 根据名称自动装配

Bean1.java

package com.cos.bean110321;

public class Bean1 {

    String name;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

 

 

Test.java

package com.cos.bean110321;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
    private Bean1 bean1;

    public Bean1 getBean1() {
        return bean1;
    }
    public void setBean1(Bean1 bean1) {
        this.bean1 = bean1;
    }
    public static void main(String[] args) {
        BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext_7.xml");//根据配置文件获得bean工厂
        Test test = (Test) factory.getBean("test");//取得test这个bean,转化成Test对象
        test.getBean1().setName("good");//给Bean1的name设置值:good
        System.out.println(""+test.getBean1().getName());//取得Bean1的name属性的值,结果输出:good
    }
}

  

 

applicationContext_7.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:amq="http://activemq.apache.org/schema/core" xmlns:jms="http://www.springframework.org/schema/jms"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd" default-autowire="byName">

    <bean name="test" class="com.cos.bean110321.Test"/>
    <bean name="bean1" class="com.cos.bean110321.Bean1"/>
</beans>

 

从这个配置文件中可以发现,test和bean1这两个bean根本没有做关联配置,但是在Test.java中可以正确的给Bean1的name赋值,并且可以取出其中的值。

原因就是在配置文件的<beans>标签中配置了一个属性: default-autowire="byName"

这样只要配置文件中bean的名字:bean1和Test.java中属性的名字Bean1可以匹配上。spring就会自动完成按名称自动匹配。就不需要我们在配置文件中指定注入关系。

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值