您的位置:首页 > 编程语言 > Java开发

Spring依赖注入的三种方式详解之三:工厂方法注入

2016-12-29 00:00 1301 查看


spring框架提供了三种方式的基于xml配置依赖注入:属性注入,构造方法注入,工厂方法注入。本文举例演示工厂方法注入。

例如有类MasterC

package com.bwf51coding.bean;

public class MasterC {
private int age;
private String name;

private MasterC(int age, String name) {
this.age=age;
this.name=name;
}
private static MasterC c;
public static MasterC getInstance(int age, String name){
if(c==null){
c=new MasterC(age, name);
}
return c;
}

@Override
public String toString() {
return "MasterC [age=" + age + ", name=" + name + "]";
}
}
applicationContext.xml配置文件配置方式如下:

<bean id="masterc" class="com.bwf51coding.bean.MasterC" factory-method="getInstance" >
<constructor-arg value="40"/>
<constructor-arg value="Alice"/>
</bean>
getInstance()方法就是一个静态工厂方法,该方法唯一实例。其中的<constructor-arg value="40"/>和<constructor-arg value="Alice"/>是传递给工厂方法的参数用于实例化对象的构造方法的参数测试类代码:

package com.bwf51coding.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bwf51coding.bean.MasterC;

public class TestC {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
MasterC masterc=(MasterC)ac.getBean("masterc");
System.out.println(masterc);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息