Spring容器ApplicationContext、BeanFactory 的使用及区别。
【IPersonService】
package com.athl.service;
public interface IPersonService {
String doFirest();
void doSecond();
}
【PersonServiceImpl】
package com.athl.service;
public class PersonServiceImpl implements IPersonService {
public PersonServiceImpl(){
System.out.println("===PersonServiceImpl构造方法===");
}
@Override
public String doFirest() {
System.out.println("执行doFirest()方法");
return null;
}
@Override
public void doSecond() {
System.out.println("执行doSecond()方法");
}
}
【applicationContext.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">
<!-- 以上约束到docs/spring-framework-reference/html/xsd-configuration.html复制 -->
<!-- 添加提示:window->preferences->查找xml->xml Catalog->User specifiled Entries
->add->引入schema\beans\spring-beans-4.2.xsd -->
<!-- 注册Service对象:相当于Java代码中的IPersonService service=new PersonServiceImpl();
这个对象是在Spring容器被初始化的时创建的
-->
<bean id="personService" class="com.athl.service.PersonServiceImpl"/>
</beans>
【test】
package com.athl.test;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import com.athl.service.IPersonService;
import com.athl.service.PersonServiceImpl;
@SuppressWarnings("deprecation")
public class Mytest {
@Test
public void test01(){
IPersonService service = new PersonServiceImpl();
service.doFirest();
service.doSecond();
}
@Test
public void test02(){
/*加载Spring配置文件,创建Spring容器对象,找的是src根目录下配置文件*/
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
/*从容器中获取指定Bean对象*/
IPersonService service = (IPersonService) ac.getBean("personService");
service.doFirest();
service.doSecond();
}
@Test
public void test03(){
/*加载Spring配置文件,创建Spring容器对象,找的是项目根目录下配置文件*/
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
/*从容器中获取指定Bean对象*/
IPersonService service = (IPersonService) ac.getBean("personService");
service.doFirest();
service.doSecond();
}
@Test
public void test04(){
/*BeanFactory容器中的对象不是在容器初始化时创建的,而是在真正使用时才创建;而ApplicationContext容器中的对象是在容器初始化时就已经创建了*/
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
/*从容器中获取指定Bean对象*/
IPersonService service = (IPersonService) bf.getBean("personService");
service.doFirest();
service.doSecond();
}
}