首頁  >  文章  >  Java  >  SpringBoot怎麼使用applicationContext.xml設定檔

SpringBoot怎麼使用applicationContext.xml設定檔

WBOY
WBOY轉載
2023-06-02 21:13:321929瀏覽

使用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"});

以上是SpringBoot怎麼使用applicationContext.xml設定檔的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除