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注入


  • 5
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值