接上篇:springboot使用PropertyResource注解读取指定配置文件的属性(传智播客代码)
@ImportResource可以加载多个配置文件
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); } }
测试结果:
本博客文章绝大多数为原创,少量为转载,代码经过测试验证,如果有疑问直接留言或者私信我。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。