/**静态工厂*/
public class StaticFactory {
public static Integer getId() {
return 1;
}
public static String getName() {
return "静态工厂";
}
public static User getUser() {
return new User(1, "工厂User", "666");
}
}
测试类代码
/** 通过静态工厂方式注入 */
public class IoC_By_StaticFactory {
private Integer id;
private String name;
private User user;
/** 检查是否注入成功 */
public Boolean checkAttr() {
if (id == null) {
return false;
} else {
System.out.println("id:" + id);
}
System.out.println("----------------------------");
if (name == null) {
return false;
} else {
System.out.println("name:" + name);
}
System.out.println("----------------------------");
if (user == null) {
return false;
} else {
System.out.println("user:" + user.getId() + "|"
+ user.getUserName() + "|" + user.getPassWord());
}
System.out.println("----------------------------");
System.out.println("全部正确!!!");
return true;
}
/**需要为需要注入的属性设置set方法*/
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setUser(User user) {
this.user = user;
}
}
applicationContext.xml配置
测试代码
public class IoC_Test {
private ApplicationContext ctx;
@Before
public void load() {
//读取applicationContext.xml配置文件
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void staticFactoryTest() {
IoC_By_StaticFactory ioc = (IoC_By_StaticFactory) ctx.getBean("ioC_By_StaticFactory");
ioc.checkAttr();
}
}
/**实例工厂*/
public class Factory {
public Integer getId() {
return 1;
}
public String getName() {
return "实例工厂";
}
public User getUser() {
return new User(1, "实例工厂User", "233");
}
}
测试类代码
/**实例工厂注入*/
public class IoC_By_Factory {
private Integer id;
private String name;
private User user;
/** 检查是否注入成功 */
public Boolean checkAttr() {
if (id == null) {
return false;
} else {
System.out.println("id:" + id);
}
System.out.println("----------------------------");
if (name == null) {
return false;
} else {
System.out.println("name:" + name);
}
System.out.println("----------------------------");
if (user == null) {
return false;
} else {
System.out.println("user:" + user.getId() + "|"
+ user.getUserName() + "|" + user.getPassWord());
}
System.out.println("----------------------------");
System.out.println("全部正确!!!");
return true;
}
/**需要为需要注入的属性设置set方法*/
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setUser(User user) {
this.user = user;
}
}
applicationContext.xml配置
测试类代码
public class IoC_Test {
private ApplicationContext ctx;
@Before
public void load() {
//读取applicationContext.xml配置文件
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void factoryTest() {
IoC_By_Factory ioc = (IoC_By_Factory) ctx.getBean("ioC_By_Factory");
ioc.checkAttr();
}
}