Spring工厂类的基本使用

Spring工厂类的基本使用

八月 19, 2019

配置文件 applicationContext.xml

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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">
<!-- UserService的创建权交给了Spring -->
<bean id="userService" class="com.imooc.ioc.demo1.UserServiceImpl">
<property name="name" value="李四"/>
</bean>
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
@Test
/**
* Spring的方式实现
*/
public void demo2(){
// 创建Spring的工厂(Spring的IOC容器对象)
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
// 通过工厂获得类:
UserService userService = (UserService) applicationContext.getBean("userService");

userService.sayHello();
}
1
2
3
4
5
6
7
8
9
10
11
12
@Test
/**
* 读取磁盘系统中的配置文件
*/
public void demo3(){
// 创建Spring的工厂类:
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("c:\\applicationContext.xml");
// 通过工厂获得类:
UserService userService = (UserService) applicationContext.getBean("userService");

userService.sayHello();
}
1
2
3
4
5
6
7
8
9
10
11
12
@Test
/**
* 传统方式的工厂类:BeanFactory
*/
public void demo4(){
// 创建工厂类:(已经过时)
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
// 通过工厂获得类:
UserService userService = (UserService) beanFactory.getBean("userService");

userService.sayHello();
}
1
2
3
4
5
6
7
8
9
10
11
12
/**
* 传统方式的工厂类:BeanFactory
*/
@Test
public void demo5(){
// 创建工厂类:
BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("c:\\applicationContext.xml"));
// 通过工厂获得类:
UserService userService = (UserService) beanFactory.getBean("userService");

userService.sayHello();
}