要引入的jar包
==其中,日志jar包不在spring官方文件中,要另外下载,链接:spring相关jar包免费下载
例子:
public class TestSpring5 {
@Test
public void testAdd(){
// spring加载配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
// 获取配置对象 创建配置对象
User user = context.getBean("user", User.class);
System.out.println(user);
user.add();
}
}
IOC接口
- 1、Spring提供IOC容器实现的两种方式:(两个接口)
- a)、BeanFactory:IOC容器基本实现,是Spring内部的使用接口,一般不提供给开发者使用
- 加载配置文件时,不会创建配置对象,在使用对象时才创建对象(用的时候才创建)
- b)、ApplicationContext:是BeanFactory接口的子接口,提供更多更强大的功能,一般由开发人员使用
- 加载配置文件时,就创建配置对象
- 这个接口比较好,将启动时间拉长(启动时就创建对象,启动时间相对较长),但使用的时间损耗减少,用户体验提升
注:两个接口都能加载spring配置文件,然后创建配置对象
- a)、BeanFactory:IOC容器基本实现,是Spring内部的使用接口,一般不提供给开发者使用
- 2、ApplicationContext接口的实现类(IDEA
Ctrl + H
查看)- 这是ApplicationContext接口的两个主要实现类
- 以下部分内容来自:https://blog.csdn.net/hbs321123/article/details/38824091
- a)、使用
FileSystemXmlApplicationContext
(文件系统
)时:-
//当前路径加载单个配置文件 ApplicationContext context = new FileSystemXmlApplicationContext("spring-config.xml"); String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"}; //同时加载多个配置文件 ApplicationContext context = new FileSystemXmlApplicationContext(locations ); //根据具体路径加载文件 ApplicationContext context = new FileSystemXmlApplicationContext("D:/project/bean.xml");
- 也就是若在Project目录下,可以不加盘符,否则,应该写入绝对路径
-
- b)、使用
ClassPathXmlApplicationContext
时 -
//加载单个配置文件 ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"}; //同时加载多个配置文件。 ApplicationContext context = new ClassPathXmlApplication(locations); //用通配符同时加载多个配置文件: 加前缀 classpath: ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/*.xml");
- 其中FileSystemXmlApplicationContext和ClassPathXmlApplicationContext与BeanFactory的xml文件定位方式一样是基于路径的。
- c)、例子
-
public static void main(String[] args) { ApplicationContext factory = null; // 用classpath路径,用ClassPathXmlApplicationContext类时,有没有classpath:前缀都是一样的。 factory = new ClassPathXmlApplicationContext("classpath:appcontext.xml"); factory = new ClassPathXmlApplicationContext("appcontext.xml"); // ClassPathXmlApplicationContext使用了file前缀是可以使用绝对路径的。 factory = new ClassPathXmlApplicationContext("file:F:/workspace/example/src/appcontext.xml"); // 用文件系统的路径,默认指项目的根路径 factory = new FileSystemXmlApplicationContext("src/appcontext.xml"); factory = new FileSystemXmlApplicationContext("webRoot/WEB-INF/appcontext.xml"); // 使用了classpath:前缀,这样,FileSystemXmlApplicationContext也能够读取classpath下的相对路径 factory = new FileSystemXmlApplicationContext( "classpath:appcontext.xml"); // 加不加file前缀都是一样的。 factory = new FileSystemXmlApplicationContext("file:F:/workspace/example/src/appcontext.xml"); factory = new FileSystemXmlApplicationContext("F:/workspace/example/src/appcontext.xml"); HelloClient hw = (HelloClient) factory.getBean("helloworldbean"); }
- 这是ApplicationContext接口的两个主要实现类