Spring02-创建容器
1. 创建容器的四种方式
- 直接new个对象。
//该方式的缺陷:当前测试类跟service实现类耦合到一起
@Test
public void testSome01() {
SomeService someService = new SomeServiceImpl();
someService.doSome();
}
- 创建ApplicationContext对象。
- SomeService service = ac.getBean(“someServiceImpl”, SomeService.class);
- "someServiceImpl"是.xml文件中bean标签中id。
- SomeService.class是service的类型的class。
- SomeService service = ac.getBean(“someServiceImpl”, SomeService.class);
@Test
public void testSome02() {
//创建容器对象,ApplicationContext初始化时,所有容器中beans创建完毕
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
SomeService service = ac.getBean("someServiceImpl", SomeService.class);
service.doSome();
}
- 创建Beanfactory对象。
@Test
public void testSome03() {
//创建容器对象,BeanFactory当调用getBean的时候获取相应对象时,才创建对象
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
SomeService service = bf.getBean("someServiceImpl", SomeService.class);
service.doSome();
}
- 创建自定义工厂,工厂里放入要拿的对象。
package com.caorui.factory;
import com.caorui.service.SomeService;
import com.caorui.service.impl.SomeServiceImpl;
public class ServiceFactory {
//实例工厂创建bean对象
public SomeService getSomeService() {
SomeService someService = new SomeServiceImpl();
return someService;
}
}
然后配置好xml文件。
<?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.xsd">
<!-- bean的定义:以下配置相当于SomeService service = new SomeServiceImpl(); id相当于service这个引用 -->
<bean id="serviceFactory" class="com.caorui.factory.ServiceFactory"></bean>
<!-- 从工厂中获取someServiceImpl的bean对象 -->
<bean id="someService" factory-bean="serviceFactory" factory-method="getSomeService"></bean>
</beans>
或者这样配置也行。
<?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.xsd">
<!-- 从工厂中获取someServiceImpl的bean对象 //静态方式 -->
<bean id="someService" class="com.caorui.factory.ServiceFactory" factory-method="getSomeService"></bean>
</beans>
serviceImpl层拿到需要的对象。
@Test
public void testSome01() {
//创建容器对象,ApplicationContext初始化时,所有容器中beans创建完毕
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
SomeService service = ac.getBean("someService", SomeService.class);
service.doSome();
}