@Propertysource 、@ImportResource和@bean 區別
- 2020 年 3 月 18 日
- 筆記
@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 { }