SpringBoot 2.x 学习(五):使用 xml 配置:@ImportResource 的使用

本文介绍了如何在SpringBoot 2.x中使用XML配置,通过创建DemoService类,定义xml文件声明对象,利用@ImportResource注解加载配置,并通过测试验证XML配置已成功注入到Spring容器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


SpringBoot 官方提倡零配置,不推荐使用 xml 配置,但是有的时候可能必须要使用 xml 配置,所以可以使用 @ImportResource 导入 xml 配置。

一、定义一个类

DemoService.java

package com.example.springbootboot02config.service;

/**
 * @author liyanan
 * @date 2019/12/22 20:03
 */
public class DemoService {
    public void add() {
        System.out.println("add() ...");
    }
}

二、在 xml 文件声明对象

demo.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 id="demoService" class="com.example.springbootboot02config.service.DemoService">
    </bean>
</beans>

在 xml 声明 demoService 对象。

三、加载 xml 配置

在 SpringBoot 启动类上使用 @ImportResource 注解的 locations 属性加载 xml 配置,将 demoService 加载入 Spring 容器。

package com.example.springbootboot02config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@ImportResource(locations = {"classpath:demo.xml"})
@SpringBootApplication
public class SpringbootBoot02ConfigApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootBoot02ConfigApplication.class, args);
    }
}

四、测试是否已将 xml 的配置加载入 Spring 容器中

package com.example.springbootboot02config;

import com.example.springbootboot02config.bean.Demo;
import com.example.springbootboot02config.bean.Emp;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.assertNotNull;

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
class SpringbootBoot02ConfigApplicationTests {
    @Autowired
    ApplicationContext applicationContext;

    @Test
    public void testDemoService() {
        Object demoService = applicationContext.getBean("demoService");
        assertNotNull(demoService);
    }

}

测试通过,证明此事 Spring 容器中已经成功注入 demoService 对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值