目录
1.ApplicationContext
4.2.BeanFactory
1.ApplicationContext
ApplicationContext的实现类,如下图:
-
ClassPathXmlApplicationContext:加载类路径下 Spring 的配置文件
-
FileSystemXmlApplicationContext:加载本地磁盘下 Spring 的配置文件
4.2.BeanFactory
-
spring中工厂的类结构图
配置文件pom.xml:
<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.1.8.RELEASE</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.30</version></dependency></dependencies>
-
区别:
-
ApplicationContext:只要一读取配置文件,默认情况下就会创建对象。
-
/*** 业务层实现类*/
public class UserServiceImpl implements UserService {private UserDao userDao;public UserServiceImpl() {System.out.println("UserServiceImpl对象创建了...");}public UserServiceImpl(UserDaoImpl userDao) {this.userDao = userDao;}public void addUser(){userDao.addUser();}
}
/*** 模拟表现层*/
public class Client {public static void main(String[] args) {new ClassPathXmlApplicationContext("applicationContext.xml");System.out.println("Spring IOC容器创建好了");}
}
BeanFactory:是在 getBean 的时候才会创建对象。
/*** 业务层实现类*/
public class UserServiceImpl implements UserService {private UserDao userDao;public UserServiceImpl() {System.out.println("UserServiceImpl对象创建了...");}public void setUserDao(UserDao userDao) {this.userDao = userDao;}public void addUser(){userDao.addUser();}
}
/*** 模拟表现层*/public class Client {public static void main(String[] args) {new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));System.out.println("Spring IOC容器创建好了");}}