@Propertysource 、@ImportResource
2020-02-20 本文已影响0人
桑鱼nicoo
@CongigurationProperties与@Propertysource结合读取指定配置文件(只能用于properties文件)
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
@Validated // 添加JSR-303 javax.validation约束注解
public class Person {
// @Value("${person.last-name}") // 从配置文件获取
@Email // lastName必须是邮箱格式
private String lastName;
@Value("#{11*2}") // 直接计算 spEL表达式
private Integer age;
@Value("true") // 字面量
private Boolean boss;
private Date birth;
private Map<String, Object> maps;
private List<Object> lists;
private Dog dog;
}
@ImportResource 导入Spring的配置文件,让配置文件里面的内容生效
SpringBoot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;通过将@ImportResource标注在一个配置类上,让Spring的配置文件生效
<?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="helloService" class="com.sangyu.springboot.service.HelloService"></bean>
</beans>
/**
* Spring 单元测试
* 可以在测试期间很方便类似编码一样进行自动注入容器等
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class MySpringBoot01ApplicationTests {
@Autowired
Person person;
@Autowired
ApplicationContext ioc;
@Test
public void contextLoads() {
System.out.println(person);
}
@Test
public void testHelloService(){
boolean b = ioc.containsBean("helloService");
System.out.println("====");
System.out.println(b);
}
}
@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
class MySpringBoot01Application {
public static void main(String[] args) {
SpringApplication.run(MySpringBoot01Application.class, args);
}
}
public class HelloService {
}