栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

加载XML配置文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

加载XML配置文件

SpringBoot提倡零配置, 即无xml配置,但是在实际开发中,可能有一些特殊要求必须使用 xml 配置; 这时我们可以通过 Spring 提供的 @importResource 来加载 xml 配置文件

1.创建业务类包和业务类service

package com.cc.springboot01init.service;

public class EmpService {
    public void  add(){
        System.out.println("add()...");
    }
}

2.resources文件下创建xml配置文件



      

      

方式:右键-》NEW-》XML Configuration File

3.应用类中导入 controller同级目录文件

关键-》@importResource(locations = {"classpath:spring01.xml"})

package com.cc.springboot01init;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.importResource;
//用于导入spring的配置文件,并将它加载到容器中
@importResource(locations = {"classpath:spring01.xml"})
@SpringBootApplication
public class SpringBoot01InitApplication {

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

}

4.测试应用中测试

package com.cc.springboot01init;

import com.cc.springboot01init.bean.Emp;
import com.cc.springboot01init.service.EmpService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;

import javax.xml.bind.SchemaOutputResolver;

@SpringBootTest
class SpringBoot01InitApplicationTests {
//    注入
    @Autowired
   ApplicationContext context;

    @Test
    void testXml() {
        EmpService empService= (EmpService)context.getBean("empService");
        System.out.println(empService);
    }

 

}

注意:测试中的导包 import org.springframework.context.ApplicationContext;

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/777871.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号