@PropertySource
可加载指定的属性配置文件到环境变量,使用参见【组件赋值】。而 @ImportSource
则可以导入 Spring 配置文件,让配置文件中内容生效。因为在 SpringBoot 中默认没有 Spring 配置文件,我们自己编写的配置文件也不能自动识别,我们如果想要使用 Spring 配置文件,此时就可以使用该注解。
1、编写示例 Spring 配置文件:
<!-- beans.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 class="com.springboot.helloworld.pojo.Dog">
<property name="name" value="bob"/>
<property name="color" value="yellow"/>
</bean>
</beans>
2、使用注解加载 Spring 配置文件:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@ImportResource("classpath:beans.xml")
public class HelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloworldApplication.class, args);
}
}
3、测试:
import com.springboot.helloworld.pojo.Dog;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* SpringBoot 单元测试
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloworldApplicationTests {
@Autowired
private Dog dog;
@Test
public void test() {
System.out.println(dog);
/*
Dog{name='bob', color='yellow'}
*/
}
}
评论区