SpringBoot入门系列篇(十二):使用XML配置Bean

前情提要

虽然SpringBoot的理念就是零配置编程,但是有时候也会出现绝对需要使用XML进行配置的情况,SpringBoot也同样提供了手动加载XML配置中的bean的方法,下面就来简单的介绍一下


在SpringBoot中简单的使用XML配置Bean

首先新建两个包,org.test1和org.test2,在org.test2包下创建一个Service,代码如下:
package test2;

import org.springframework.stereotype.Service;

/**
 * 使用XML进行配置的Service
 * @author chengxi
 */
@Service
public class HelloService {

    public HelloService(){
        System.out.println("使用XML进行配置的Service");
    }
}
然后在org.test1包下创建启动类,代码如下:
package org.test1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

/**
 * 启动类测试
 * @author chengxi
 */
@SpringBootApplication
public class Main {

    @Autowired
    private HelloService helloService;

    public static void main(String[] args){

        SpringApplication.run(Main.class, args);
    }
}
这个时候我们可以看到,如果不进行任何配置,在启动Main之后是无法访问到Service的,我们可以采用前面所说的改变自动扫描的包,在这里,我们使用XML进行配置,首先创建一个XML配置文件:
//classpath:personal.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--
        自定义配置bean
    -->
    <bean id="helloService" class="org.test2.HelloService">
    </bean>

</beans>
在创建了XML配置文件配置好了bean之后,此时还是无法访问Service的,因为SpringApplication不会自动扫描并解析XML,所以还需要创建一个配置类,代码如下:
package org.test1;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration

/**
 * ImportResource引入资源文件有三种方式:
 *     1.直接引入,该路径就是src/resources/下面的文件:file
 *     2.classpath引入:该路径就是src/java下面的配置文件:classpath:file
 *     3.引入本地文件:该路径是一种绝对路径:file:D://....
 */
@ImportResource(locations = {"personal.xml"})
public class ConfigClass {
}
这里需要注意的是,上面的配置类一定要是启动类能够扫描的到的,否则就没有用。现在run启动类,将会在控制台中输出HelloService构造器中的内容,表示此时成功完成该Service的XML注入


猜你喜欢

转载自blog.csdn.net/qq_27905183/article/details/79080699
今日推荐