springboot中xml配置之@ImportResource

springboot中进行相关的配置往往有java配置和xml配置两种方式。

使用java的方式配置只需要使用@configuration注解即可,而使用xml的方式配置的话需要使用@ImportResource来加载配置文件

不过多描述,直接以一个很简单的通过xml配置注入bean的例子来展示@ImportResource注解的使用

xml配置放在resources目录下

<?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="hello" class="com.example.yang.bean.Hello"/>
 

</beans>

新增一个配置类,导入xml配置

@ImportResource("classpath:beans.xml")
@Configuration
public class BeansConfig {
    
}

然后在使用的时候直接注入即可

@RestController
public class TestController {
    
    @Autowired
    private Hello hello;
    
    
    @RequestMapping("/hello")
    public String say() {
        return hello.say("小明");
    }
}
原文地址:https://www.cnblogs.com/xtuxiongda/p/11181679.html