1.普通的通过构造函数初始化,没有指定构造函数参数的就是用默认的无参的构造方法
<bean /> <bean name="anotherExample" class="examples.ExampleBeanTwo"/>
构造函数的几种方式:
1.普通沟通函数注入方式,按照构造函数参数的顺序和个数来注入bean
package x.y;
public class Foo {
public Foo(Bar bar, Baz baz) {
// ...
}
}
<beans>
<bean >
<constructor-arg ref="bar"/>
<constructor-arg ref="baz"/>
</bean>
<bean />
<bean />
</beans>
package examples;
public class ExampleBean {
// No. of years to the calculate the Ultimate Answer
private int years;
// The Answer to Life, the Universe, and Everything
private String ultimateAnswer;
public ExampleBean(int years, String ultimateAnswer) {
this.years = years;
this.ultimateAnswer = ultimateAnswer;
}
}
2.按照构造函数的参数类型匹配注入
<bean > <constructor-arg type="int" value="7500000"/> <constructor-arg type="java.lang.String" value="42"/> </bean>
3.按照参数索引顺序注入
<bean > <constructor-arg index="0" value="7500000"/> <constructor-arg index="1" value="42"/> </bean>
4. spring3以上还可以通过参数名称进行注入
<bean > <constructor-arg name="years" value="7500000"/> <constructor-arg name="ultimateanswer" value="42"/> </bean>
5.spring3以上通过annotation注入
@ConstructorProperties package examples;
public class ExampleBean {
// Fields omitted
@ConstructorProperties({"years", "ultimateAnswer"})
public ExampleBean(int years, String ultimateAnswer) {
this.years = years;
this.ultimateAnswer = ultimateAnswer;
}
}
6.spring3.1以上还可以使用简化的c namespace来进行构造函数注入
<bean >
c:_index方式注入
<-- 'c-namespace' index declaration --> <bean >
2.通过静态的工厂方法生成bean,这种方式在配置文件中没有指定返回的bean的类型
<bean
class="examples.ClientService"
factory-method="createInstance"/>
public class ClientService {
private static ClientService clientService = new ClientService();
private ClientService() {}
public static ClientService createInstance() {
return clientService;
}
}
3.通过实例化的工厂方法生成bean
<!-- the factory bean, which contains a method called createInstance() -->
<bean >
<!-- inject any dependencies required by this locator bean -->
</bean>
<!-- the bean to be created via the factory bean -->
<bean
factory-bean="serviceLocator"
factory-method="createClientServiceInstance"/>
public class DefaultServiceLocator {
private static ClientService clientService = new ClientServiceImpl();
private DefaultServiceLocator() {}
public ClientService createClientServiceInstance() {
return clientService;
}
}
当然这个实例化的工厂类也可以生成多个bean
<bean >
<!-- inject any dependencies required by this locator bean -->
</bean>
<bean
factory-bean="serviceLocator"
factory-method="createClientServiceInstance"/>
<bean
factory-bean="serviceLocator"
factory-method="createAccountServiceInstance"/>
public class DefaultServiceLocator {
private static ClientService clientService = new ClientServiceImpl();
private static AccountService accountService = new AccountServiceImpl();
private DefaultServiceLocator() {}
public ClientService createClientServiceInstance() {
return clientService;
}
public AccountService createAccountServiceInstance() {
return accountService;
}
}