Spring实例化JavaBean的方式有三种:使用类构造器实例化、使用静态工厂方法实例化、使用实例化工厂实例化
package test.spring.service;
public interface PersonService {
public abstract void save();
}
package test.spring.service.impl;
import test.spring.service.PersonService;
public class PersonServiceBean implements PersonService {
@Override
public void save(){
System.out.println("=============");
}
}
package test.spring.service.impl;
public class PersonServiceBeanFactory {
// 静态工厂方法
public static PersonServiceBean createPersonServiceBean() {
return new PersonServiceBean();
}
// 实例工厂方法
public PersonServiceBean createPersonServiceBean2() {
return new PersonServiceBean();
}
}使用实例化工厂方法需先配置工厂类,再配置工厂方法。用得最多的是第一种。
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
factory-method="createPersonServiceBean">
factory-method="createPersonServiceBean2">
package test.spring.jnit;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import test.spring.service.PersonService;
public class SpringTest {
@Test
public void testInstanceSpring() {
// ApplicationContext applicationContext = new
// ClassPathXmlApplicationContext(
// new String[] { "beans.xml" });
//使用类构造器实例化,用的是默认构造函数
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"beans.xml");
// PersonService personService = (PersonService) applicationContext
// .getBean("personService");// 得到的是Object,需进行转换
// BeanManageTest beanManageTest = new BeanManageTest("beans.xml");
// PersonService personService = (PersonService) beanManageTest
// .getBean("personService");// 得到的是Object,需进行转换
// 使用静态工厂方法实例化
// PersonService personService = (PersonService) applicationContext
// .getBean("personService2");
// 使用实例化工厂实例化
PersonService personService = (PersonService) applicationContext
.getBean("personService3");
personService.save();
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。如需转载,请注明出处:http://blog.csdn.net/lindonglian
原文:http://blog.csdn.net/lindonglian/article/details/47018047