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就会自动完成按名称自动匹配。就不需要我们在配置文件中指定注入关系。
本文介绍Spring框架中如何使用default-autowire属性实现自动装配Bean,通过一个简单的例子展示了当配置文件中的bean名称与类中的属性名称相同时,Spring能够自动完成依赖注入。
1884

被折叠的 条评论
为什么被折叠?



