静态工厂注入
在 spring 中,也可以使用静态工厂的方式实例化 bean。此种方式需要提供一个静态工厂方法创建 bean 的实例。
① 创建实体类
public class person{
string name;
public void setname(string name){
this.name = name;
}
}② 创建静态工厂类
创建一个名为 mybeanfactory 的类,并在该类中创建一个名为 createbean() 的静态方法,用于创建 bean 的实例,如下所示。
public class mybeanfactory {
// 创建bean实例的静态工厂方法
public static person createbean() {
person person = new person();
person.setname("glp");
return person;
}
}③ 创建 spring 配置文件
创建 spring 的配置文件 applicationcontext.xml。
<?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.2.xsd">
<bean id="person" class="com.mengma.instance.static_factory.mybeanfactory"
factory-method="createbean" />
</beans>上述代码中,定义了一个 id 为 person 的 bean,其中 class 属性指定了其对应的工厂实现类为 mybeanfactory,而 factory-method 属性用于告诉 spring 容器调用工厂类中的 createbean() 方法获取 bean 的实例。
实例工厂注入
在 spring 中,还有一种实例化 bean 的方式就是采用实例工厂,直接在成员方法中创建 bean 的实例。
同时,在配置文件中,需要实例化的 bean 也不是通过 class 属性直接指向其实例化的类,而是通过 factory-bean 属性配置一个实例工厂,然后使用 factory-method 属性确定使用工厂中的哪个方法。
① 创建实体类
public class person{
string name;
public void setname(string name){
this.name = name;
}
}② 创建实例工厂类
创建一个名为 mybeanfactory 的类。
public class mybeanfactory {
public mybeanfactory() {
system.out.println("person3工厂实例化中");
}
// 创建bean的方法
public person createbean() {
person person = new person();
person.setname("cbj");
return person;
}
}③ 创建 spring 配置文件
创建 spring 的配置文件 applicationcontext.xml,如下所示。
<?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.2.xsd">
<!-- 配置实例工厂 -->
<bean id="mybeanfactory" class="com.mengma.instance.factory.mybeanfactory" />
<!-- factory-bean属性指定一个实例工厂,factory-method属性确定使用工厂中的哪个方法 -->
<bean id="person" factory-bean="mybeanfactory" factory-method="createbean" />
</beans>上述代码中,首先配置了一个实例工厂 bean,然后配置了需要实例化的 bean。
在 id 为 person的 bean 中,使用 factory-bean 属性指定一个实例工厂,该属性值就是实例工厂的 id 属性值。
使用 factory-method 属性确定使用工厂中的 createbean() 方法。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论