springboot使用ImportResource注解加载spring配置文件(尚硅谷)

接上篇:springboot使用PropertyResource注解读取指定配置文件的属性(传智播客代码)
@ImportResource可以加载多个配置文件

springboot使用ImportResource注解加载spring配置文件(尚硅谷)_第1张图片


DemoApplication.java
package com.atguigu;

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

@ImportResource(locations = "classpath:beans.xml")
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {

        SpringApplication.run(DemoApplication.class, args);
    }

}

beans.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="helloService" class="com.atguigu.service.HelloService"/>
beans>

HelloService.java

package com.atguigu.service;

public class HelloService {
}

测试用例

package com.atguigu;


import lombok.extern.slf4j.Slf4j;
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.SpringRunner;

import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
class DemoApplicationTests {

  
    @Autowired
    ApplicationContext context;


    @Test
    void containsBeanTest()
    {
        boolean contains = context.containsBean("helloService");
        log.info("是否存在HelloService的实例:{}",contains);
    }

}

测试结果:

 

你可能感兴趣的:(springboot使用ImportResource注解加载spring配置文件(尚硅谷))