BeanFactory和ApplicationContext的区别
程序员文章站
2022-03-03 12:37:24
...
<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">
<!-- xml文件配置 -->
<bean id = "userDao" class="com.itheima.dao.Impl.UserDaoImpl"></bean>
<bean id = "userService" class="com.itheima.service.Impl.UserServiceImpl"></bean>
</beans>
@org.junit.Test
public void comparefa(){
ClassPathResource resource = new ClassPathResource("beans.xml");
//beanFactory:创建容器对象时只是加载配置文件,没有创建对象,即使路径错误也不会报错,只有运行的时候才会报错
//获取对象时创建对象
XmlBeanFactory beanFactory = new XmlBeanFactory(resource);
Object userDao = beanFactory.getBean("userDao");
System.out.println(userDao);
//ApplicationContext:在创建容器对象时创建对象 (常用)
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
Object userDao1 = applicationContext.getBean("userDao");
System.out.println(userDao1);
}