模式 | 说明 |
no | 这是默认的自动装配模式。这意味着默认情况下没有自动装配。 |
byName | byName模式根据bean的名称注入对象依赖项。在这种情况下,属性名称和bean名称必须相同。它在内部调用setter方法。 |
byType | byType模式根据类型注入对象依赖项。因此属性名称和bean名称可以不同。它在内部调用setter方法。 |
constructor | 构造函数模式通过调用类的构造函数来注入依赖项。它会调用具有大量参数的构造函数。 |
autodetect | 从Spring 3开始不推荐使用。 |
<bean id="a" class="org.sssit.A" autowire="byName"></bean>
B.java
A.java
applicationContext.xml
Test.java
package org.sssit; public class B { B(){System.out.println("b is created");} void print(){System.out.println("hello b");} }
package org.sssit; public class A { B b; A(){System.out.println("a is created");} public B getB() { return b; } public void setB(B b) { this.b = b; } void print(){System.out.println("hello a");} void display(){ print(); b.print(); } }
<?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-3.0.xsd"> <bean id="b" class="org.sssit.B"></bean> <bean id="a" class="org.sssit.A" autowire="byName"></bean> </beans>
package org.sssit; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); A a=context.getBean("a",A.class); a.display(); } }
b is created a is created hello a hello b
<bean id="b" class="org.sssit.B"></bean> <bean id="a" class="org.sssit.A" autowire="byName"></bean>
<bean id="b1" class="org.sssit.B"></bean> <bean id="a" class="org.sssit.A" autowire="byName"></bean>
<bean id="b1" class="org.sssit.B"></bean> <bean id="a" class="org.sssit.A" autowire="byType"></bean>
<bean id="b1" class="org.sssit.B"></bean> <bean id="b2" class="org.sssit.B"></bean> <bean id="a" class="org.sssit.A" autowire="byName"></bean>
<bean id="b" class="org.sssit.B"></bean> <bean id="a" class="org.sssit.A" autowire="constructor"></bean>
<bean id="b" class="org.sssit.B"></bean> <bean id="a" class="org.sssit.A" autowire="no"></bean>