springboot引入XML配置

论坛 期权论坛 脚本     
已经匿名di用户   2022-2-7 16:34   1825   0

首先理清逻辑:

  1. 引入xml配置就要有xml
  2. xml有对应的内容
  3. 该xml需要被引用,或者说被导入到配置中
  4. 让xml生效的配置
  5. 让启动类扫描到配置类

所以我们首先需要建一个xml配置

假设我们写一个类,然后把该类注入到xml里面被引用好了,该类不在启动类的扫描范围之内,所以我们在application.java的同级目录下建一个包写一个类:

package com.testjunit;


public class TestService {
    public TestService(){
        System.out.println("这是一个测试范围外的类");
    }

}

接下来就是xml的bean中对应,在resources里面写一个application-bean.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-3.0.xsd ">
    <bean id="testService" class="com.testjunit.TestService"></bean>
</beans>

然后我们写一个配置类Config.java,引用该xml:

package com.example.demo.config;

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

@Configuration
@ImportResource(locations = {"classpath:application-bean.xml"})
public class Config {

}

然后启动项目,引入成功:

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP