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