首页 > 编程技术 > java

SpringBoot如何使用applicationContext.xml配置文件

发布时间:2022-6-27 15:32 作者:我是你亲爱的航哥

使用applicationContext.xml配置文件

SpringBoot默认是通过Java代码进行依赖注入,但也为xml形式的依赖注入提供了入口,就是@ImportResource注解。

我们可以在SpringBoot的启动类上添加这个注解并在注解的locations属性中指定xml配置文件。(可以使用一个文件集合也可以只引入主配置文件然后在主配置文件中使用标签引入其他子配置文件,个人更喜欢第二中方式)。

这样容器在启动时配置在xml文件中的BeanDefination也可以被解析。 

applicationContext 加载配置文件

ApplicationContext 理解为spring容器的上下文,通过上下文操作容器中bean.

案例

/*方式一 :ClassPathXmlApplicationContext*/
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring.xml");
/*方式二 FileSystemXmlApplicationContext */
        //FileSystemXmlApplicationContext ioc= new FileSystemXmlApplicationContext("E://1804_2//20180827spring//config//spring.xml");
        User u = (User) ioc.getBean("user1");
        System.out.println(u);

多文件的加载方法

/*方式一*/
//ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring.xml,spring-mvc.xml");
/*方式二*/
//ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext(new String[]{"spring.xml,spring-mvc.xml"});
/*方式三*/
//ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring-*.xml");
/*方式四*/
//ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext(new String []{"classpath:spring-*.xml","mybatis.xml"});
/*方式五*/
//ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("classpath:*.xml");
/*方式六*/
//ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("classpath*:*.xml");
/*方式七*/
//ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext(new String []{"classpath:*.xml","classpath:springmvc/beans.xml"});

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。

原文出处:https://blog.csdn.net/qq_28807077/article/details/105100249

标签:[!--infotagslink--]

您可能感兴趣的文章: