SpringBoot理念就是零配置编程,但是如果绝对需要使用XML的配置,我们建议您仍旧从一个@Configuration类开始,你可以使用@ImportResouce注解加载XML配置文件,我拿一个例子来进行讲解:
这个例子的大体步骤如下:
(1)新建一个工程;
(2)在App.java类编写HelloService2;
(3)在App.java类无法扫描的包下编写HelloService;
(4)编写application-bean.xml注入HelloService;
(5)编写ConfigClass注入配置文件application-bean.xml;
(6)编写App.java启动类进行测试;
(7)其它说明
(1)新建一个工程;
我们在前几节的例子已经写到hello2了,我们取一个新的名称为spring-boot-hello3,这里没有什么难点,不过多介绍,还有难处的可以查看之前的例子,当然这里加入spring-boot相应的web支持;
不懂的参考:
spring boot起步之Hello World【从零开始学Spring Boot】:
http://412887952-qq-com.iteye.com/blog/2291500
(2)在App.java类编写HelloService2;
首先我们这里有几个包:com.kfit,org.kfit,我们这里打算把App.java启动类放到com.kfit中,根据Spring Boot扫描(根包到子包的原则),我们把HelloService2写在Spring Boot可以扫描的位置,HelloService写在Spring Boot无法扫描到的位置,那么我们使用配置文件bean的方式进行引入,具体代码如下:
com.kfit.service.HelloService2:
package com.kfit.service;
importorg.springframework.stereotype.Service;
@Service
publicclass HelloService2 {
/**
*启动的时候观察控制台是否打印此信息;
*/
publicHelloService2() {
System.out.println("HelloService2.HelloService2()");
System.out.println("HelloService2.HelloService2()");
System.out.println("HelloService2.HelloService2()");
}
}
(3)在App.java类无法扫描的包下编写HelloService;
注意这个类是写在Spring Boot无法自动扫描的位置,正常启动之后,如果引入HelloService的话肯定会报异常的,因为它根本没有被注入成功,具体代码如下:
org.kfit.service.HelloService:
package org.kfit.service;
importorg.springframework.stereotype.Service;
@Service
publicclass HelloService {
/**
*启动的时候观察控制台是否打印此信息;
*/
public HelloService(){
System.out.println("HelloService.HelloService()");
System.out.println("org.kfit.service.HelloService.HelloService()");
System.out.println("HelloService.HelloService()");
}
}
(4)编写application-bean.xml注入HelloService;
在src/main/resouces下编写配置文件application-bean.xml文件:
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="" target="_blank">http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"" target="_blank">>
<!-- 注入spring boot无法扫描到的bean. -->
<bean id="helloService"class="org.kfit.service.HelloService"></bean>
</beans>
。。。。。。。。。。。。。。。。。
版权原因,完整文章,请参考如下:31. Spring Boot导入XML配置【从零开始学Spring Boot】