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("小明");
    }
}

 

相关文章:

  • 2021-10-26
  • 2022-12-23
  • 2021-12-30
  • 2021-10-21
  • 2021-05-29
  • 2021-09-29
  • 2021-04-27
  • 2022-12-23
猜你喜欢
  • 2022-01-27
  • 2022-12-23
  • 2022-12-23
  • 2021-06-29
  • 2022-12-23
  • 2021-04-26
  • 2022-12-23
相关资源
相似解决方案