spring Bean的三种注入方式

时间:2022-03-25 12:57:47

1、构造函数注入:

构造函数的注入方式分为很多种

(1)普通构造函数,空参数的构造函数

<bean id="exampleBean" class="examples.ExampleBean"/>  

(2)根据构造函数的参数顺序和个数

package com.my.bean;

public class Foo {

  public Foo(Bar bar, Baz baz) {
// ...
}
}
<beans>
<bean id="foo" class="com.my.bean.Foo">
<constructor-arg ref="bar"/>
<constructor-arg ref="baz"/>
</bean> <bean id="bar" class="com.my.bean.Bar"/>
<bean id="baz" class="com.my.bean.Baz"/> </beans>

(3)根据构造函数的参数类型匹配

<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg type="int" value="7500000"/>
<constructor-arg type="java.lang.String" value="42"/>
<constructor-arg type="java.lang.Boolean" value="false"/>
</bean>

(4)根据构造函数的参数索引顺序和个数

<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg index="0" value="3000"/>
<constructor-arg index="1" value="42"/>
</bean>

(5)spring3以上还可以通过参数名称进行注入

<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg name="age" value="25"/>
<constructor-arg name="name" value="jerry"/>
</bean>

2、静态工厂方法注入

<bean id="clientService"
class="examples.ClientService"
factory-method="getInstance"/>
public class ClientService {

  public static ClientService getInstance() {
return new clientService();
}
}

3、实例化的工厂方法注入

public class MyServiceFactory {

    public MyServiceBean createMyServiceBean(){

        return new MyServiceBean();
}
}
<bean id="myServiceFactory" class="com.my.bean.MyServiceFactory"></bean>

<bean id="personService" factory-bean="myServiceFactory" factory-method="createMyServiceBean"></bean>