通过配置default-autowire 属性,Spring IOC 容器可以自动为程序注入bean;默认是no,不启用自动装配;
default-autowire 的类型有byName,byType,constructor;
byName:通过名称进行自动匹配;
byType:根据类型进行自动匹配;
constructor:和byType 类似,只不过它是根据构造方法注入而言的,根据类型,自动注入;
<beans......default-autowire="constructor">
Spring bean 作用域默认是单例singleton; 可以通过配置prototype ,实现多例;
方法注入lookup-method
package entity;
public class Dog {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public abstract class People { private int id; private String name; private int age; private Dog dog; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public abstract Dog getDog(); public void setDog(Dog dog) { this.dog = dog; } @Override public String toString() { return "People [id=" + id + ", name=" + name + ", age=" + age + ", dog=" + dog.getName() + "]"; } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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.xsd"> <!-- 每次都生成新的bean --> <bean id="dog" class="entity.Dog" scope="prototype"> <property name="name" value="Jack"></property> </bean> <bean id="people1" class="entity.People"> <property name="id" value="1"></property> <property name="name" value="张三"></property> <property name="age" value="11"></property> <lookup-method name="getDog" bean="dog"/> </bean> </beans>