Spring Boot @PropertySource&@ImportResource&@Bean註解
阿新 • • 發佈:2019-01-14
一[email protected]:載入指定的配置檔案
例如:載入person.properties
person.properties內容:
person.last-name=李四
person.age=18
person.birth=2019/01/07
person.boss=true
person.maps.k1=v1
person.maps.k2=15
person.lists=a,b,c
person.dog.name=小狗
person.dog.age=5
測試載入相關程式碼Person實體類
@PropertySource(value = {"classpath:person.properties"}) @Component @ConfigurationProperties(prefix = "person") @Validated public class Person { private String lastName; private Integer age; private Boolean boss; private Date birth; private Map<String,Object> maps; private List<Object> lists; private Dog dog; ... }
執行單元測試程式碼
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02ConfigApplicationTests {
@Autowired
Person person;
@Test
public void contextLoads() {
System.out.println(person);
}
}
執行結果:
二[email protected]:匯入Spring的配置檔案,讓配置檔案裡面的內容生效
Spring Boot裡面沒有Spring的配置檔案,我們自己編寫的配置檔案,也不能自動識別;想讓Spring的配置檔案生效,載入進來;@ImportResource標註在一個配置類上
例如:載入beans.xml
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 id="helloService" class="com.hq.springboot.service.HelloService"></bean> </beans>
在啟動方法中加入自定義配置
@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringBoot02ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot02ConfigApplication.class, args);
}
}
啟動單元測試方法
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02ConfigApplicationTests {
@Autowired
Person person;
@Autowired
ApplicationContext ioc;
@Test
public void testHelloService(){
boolean helloService = ioc.containsBean("helloService");
System.out.println(helloService);
}
@Test
public void contextLoads() {
System.out.println(person);
}
}
列印結果:注入成功
三[email protected]
SpringBoot推薦給容器中新增元件的方式;推薦使用全註解的方式
1、配置類@Configuration------>Spring配置檔案
2、使用@Bean給容器中新增元件
例如載入配置類MyAppConfig.java
MyAppConfig.java內容
/**指明當前類是一個配置類:替代之前的Spring配置檔案
* 在配置檔案中用<bean><bean/>標籤新增元件
* @author hq.zheng
* @create 2019-01-08-下午 10:38
*/
@Configuration
public class MyAppConfig {
//將方法的返回值新增到容器中;容器中這個元件預設的id就是方法名
@Bean
public HelloService helloService(){
System.out.println("配置類@Bean給容器中新增元件了...");
return new HelloService();
}
}
執行單元測試方法
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02ConfigApplicationTests {
@Autowired
Person person;
@Autowired
ApplicationContext ioc;
@Test
public void testHelloService(){
boolean helloService = ioc.containsBean("helloService");
System.out.println(helloService);
}
@Test
public void contextLoads() {
System.out.println(person);
}
}
執行結果: