2022.5.20

在主启动类上使用 @ImportResource 注解可以导入一个或多个 Spring 配置文件,并使其中的内容生效。

1. 以 helloworld 为例,在 net.biancheng.www.service 包下创建一个名为 PersonService 的接口,代码如下。

  1. package net.biancheng.www.service;
  2. import net.biancheng.www.bean.Person;
  3. public interface PersonService {
  4. public Person getPersonInfo();
  5. }

 
2. 在 net.biancheng.www.service.impl 包下创建一个名为 PersonServiceImpl 的类,并实现 PersonService 接口,代码如下。

  1. package net.biancheng.www.service.impl;
  2. import net.biancheng.www.bean.Person;
  3. import net.biancheng.www.service.PersonService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. public class PersonServiceImpl implements PersonService {
  6. @Autowired
  7. private Person person;
  8. @Override
  9. public Person getPersonInfo() {
  10. return person;
  11. }
  12. }


3. 在该项目的 resources 下添加一个名为 beans.xml 的 Spring 配置文件,配置代码如下。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <bean id="personService" class="net.biancheng.www.service.impl.PersonServiceImpl"></bean>
  6. </beans>


4. 修改该项目的单元测试类 HelloworldApplicationTests ,校验 IOC 容器是否已经 personService,代码如下。

  1. package net.biancheng.www;
  2. import net.biancheng.www.bean.Person;
  3. import org.junit.jupiter.api.Test;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.context.ApplicationContext;
  7. @SpringBootTest
  8. class HelloworldApplicationTests {
  9. @Autowired
  10. Person person;
  11. //IOC 容器
  12. @Autowired
  13. ApplicationContext ioc;
  14. @Test
  15. public void testHelloService() {
  16. //校验 IOC 容器中是否包含组件 personService
  17. boolean b = ioc.containsBean("personService");
  18. if (b) {
  19. System.out.println("personService 已经添加到 IOC 容器中");
  20. } else {
  21. System.out.println("personService 没添加到 IOC 容器中");
  22. }
  23. }
  24. @Test
  25. void contextLoads() {
  26. System.out.println(person);
  27. }
  28. }
posted @ 2022-05-20 13:55  小强哥in  阅读(19)  评论(0编辑  收藏  举报