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();
}
}
使用实例化工厂方法需先配置工厂类,再配置工厂方法。用得最多的是第一种。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<!-- 这时候这个bean就可以由spring帮我们创建和维护,用到时只需从spring容器中获取 -->
<bean id="personService" class="test.spring.service.impl.PersonServiceBean"></bean>
<bean id="personService2" class="test.spring.service.impl.PersonServiceBeanFactory"
factory-method="createPersonServiceBean"></bean>
<bean id="personServiceFactory" class="test.spring.service.impl.PersonServiceBeanFactory"></bean>
<bean id="personService3" factory-bean="personServiceFactory"
factory-method="createPersonServiceBean2"></bean>
</beans>
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();
}
}