spring的装配方式有很多种,我主要学习了下autowire=byType,byName,constructor的用法。他们的配置文件和代码如下:
类文件
public class Person {
private String name;
private Home myhome;
public Person(Home myhome){
this.myhome = myhome;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Home getMyhome() {
return myhome;
}
public void setMyhome(Home myhome) {
this.myhome = myhome;
}
}
package com.autowire;
public class Home {
private String addr;
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
}
byName装配:根据person类里有myhome属性,而且没有通过设值注入,spring容器会根据名字相同找到配置的属性。
<bean id="person" class="com.autowire.Person" autowire="byName">
<property name="name" value="james"></property>
</bean>
<bean id="myhome" class="com.autowire.Home">
<property name="addr" value="hongkong"></property>
</bean>
byType装配:根据person里有myhome的类型,在容器里找到类型相同的bean,并把值注入。注意容器里只能有一个相同的bean类型,如果多于一个就会报异常。如果没有就什么都不做。
<bean id="person" class="com.autowire.Person" autowire="byType">
<property name="name" value="james"></property>
</bean>
<bean id="myhome" class="com.autowire.Home">
<property name="addr" value="hongkong"></property>
</bean>
constructor装配:通过类里提供的构造函数来装配,这个构造函数里只能提供一个所需的属性作为参数,多了就会报异常。
<bean id="person" class="com.autowire.Person" autowire="constructor">
<property name="name" value="james"></property>
</bean>
<bean id="myhome" class="com.autowire.Home">
<property name="addr" value="hongkong"></property>
</bean>
测试方法:
public class TestMain {
public static void main(String [] args){
ApplicationContext ac = new ClassPathXmlApplicationContext("autowire.xml");
Test t = (Test)ac.getBean("test");
System.out.println(t.getStr()+"******"+t.getTime());
Person p = (Person)ac.getBean("person");
System.out.println(p.getName()+"+++"+p.getMyhome().getAddr());
}
}