Spring Boot-通过@ImportResource注解引入配置Bean的XML

有一个接口类Animal,如下:

public interface Animal {
    void eat();
}

有一个实现类Cat,如下:

@Service
public class Cat implements Animal {

    public Cat() {
        System.out.println("延迟依赖注入");
    }

    @Override
    public void eat() {
        System.out.println("猫吃鱼");
    }
}

有一个测试controller,它注入了Animal,如下:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class ServiceController {
    @Autowired
    @Qualifier("cat")
    private Animal animal;

    @GetMapping
    public void eat() {
        animal.eat();
    }
}

由于Cat这个类不在包扫描路径下,所以启动会报错,如下:
在这里插入图片描述
这里使用xml配置文件加上@ImportResource注解来配置bean,新建spring-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.xsd">
    <bean id="cat" class="com.example.springboot.mycache.Cat"/>
</beans>

在启动类上添加@ImportResource注解,导入相应的xml文件,如下:
在这里插入图片描述
间接的把xml文件里定义的bean装配到Spring IOC容器中。

重启服务,访问接口,结果如下:
在这里插入图片描述
通过@ImportResource注解引入配置Bean的XML文件成功。

猜你喜欢

转载自blog.csdn.net/weixin_38106322/article/details/107850882