PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

SpringBoot怎么使用applicationContext.xml配置文件

WBOY
WBOY 转载
2023-06-02 21:13:32 1757浏览

使用applicationContext.xml配置文件

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

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

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

applicationContext 加载配置文件

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

  • ClassPathXmlApplicationContext:加载classpath下的配置文件创建一个容器实例

  • FileSystemXmlApplicationContext: 加载文件系统中任意目录下的配置文件,创建一个容器实例

案例

/*方式一 :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"});
声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除