spring学习笔记整理--03(Spring的三种实例化Bean的方式)
Spring有三种实例化Bean的方式
一.构造器注入实例化
前面一个帖子的实现就是用构造器实现,也是最普遍用到的一种,在此不过多的描述。
<bean id="personService" class="cn.service.impl.PersonServiceImpl"></bean>
二.使用静态工厂方法实例化
PersonServiceFactory :
package cn.service.impl;
public class PersonServiceFactory {
public static PersonServiceImpl createPersonServiceImpl(){
return new PersonServiceImpl();
}
}
---------------------------------------------------------------
<?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 id="personService" class="cn.service.impl.PersonServiceFactory" factory-method="createPersonServiceImpl"></bean>
</beans>
---------------------------------------------------------------
package junit.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import commons.tz.TzClassPathXmlApplicationContext;
import cn.service.PersonService;
public class Spring02Test {
@Test
public void instanceSping() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService = (PersonService) ctx.getBean("personService");
personService.save();
}
}
三.使用实例工厂方法实例化
PersonServiceFactory :
package cn.service.impl;
public class PersonServiceFactory {
public PersonServiceImpl createPersonServiceImpl(){
return new PersonServiceImpl();
}
}
-------------------------------------------------------------------------
<?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 id="personServiceFactory" class="cn.service.impl.PersonServiceFactory"></bean>
<bean id="personService" factory-bean="personServiceFactory" factory-method="createPersonServiceImpl"></bean>
</beans>
-------------------------------------------------------------------------
package junit.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import commons.tz.TzClassPathXmlApplicationContext;
import cn.service.PersonService;
public class Spring02Test {
@Test
public void instanceSping() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService = (PersonService) ctx.getBean("personService");
personService.save();
}
}
今天学的不多,偷个懒!
浙公网安备 33010602011771号