首先理清逻辑:
- 引入xml配置就要有xml
- xml有对应的内容
- 该xml需要被引用,或者说被导入到配置中
- 让xml生效的配置
- 让启动类扫描到配置类
所以我们首先需要建一个xml配置
假设我们写一个类,然后把该类注入到xml里面被引用好了,该类不在启动类的扫描范围之内,所以我们在application.java的同级目录下建一个包写一个类:
package com.testjunit;
public class TestService {
public TestService(){
System.out.println("这是一个测试范围外的类");
}
}
接下来就是xml的bean中对应,在resources里面写一个application-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-3.0.xsd ">
<bean id="testService" class="com.testjunit.TestService"></bean>
</beans>
然后我们写一个配置类Config.java,引用该xml:
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource(locations = {"classpath:application-bean.xml"})
public class Config {
}
然后启动项目,引入成功: