2020年11月23日 星期一

[SpringBoot 1.5] 配置 @PropertySource、@ImportResource、@Bean

 我們前面看過@ConfigurationProperties與application.properties的合用方式

那如果我們有一些配置文件想要單獨提取出來使用

可以另外產生一個properties檔案專為其使用

以下我們先產生一個person.properties檔案如下

person.lastname=李四
person.age=18
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=dog
person.dog.age=15

然後我們在原本的類別上加入@PropertySource

@PropertySource:加載指定配置文件

@PropertySource(value={"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {

//@Value("${person.lastname}")
//@Email
private String lastname;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String, Object> maps;
private List<Object> lists;
private Dog dog;

這裡不同的是要給value, 裡面放classpath加指定

@ImportResource: 導入Spring的配置文件, 讓配置文件裡面的內容生效

由於Spring Boot裡面沒有Spring的配置文件, 我們自己編寫的配置文件, 也不能自動識別;

想讓Spring的配置文件生效, 加載進來; @ImportResource標註在一個配置類上

首先先造一個類為 service.HelloService

public class HelloService {
}

接下來產生一個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.atguigu.springboot.service.HelloService"></bean>
</beans>

然後在測試類中加入以下

@Autowired
ApplicationContext ioc;

@Test
public void testHelloService(){
boolean b= ioc.containsBean("helloService");
System.out.println(b);
}

我們會發現結果印出來為false

這是因為剛才提到的Spring Boot 裡面沒有Spring配置文件

如果需要使用到

我們要在SpringBootApplication的類上面加入以下這段

@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringBoot02ConfigApplication {

public static void main(String[] args) {
SpringApplication.run(SpringBoot02ConfigApplication.class, args);
}

}

我們會發現, 這樣run test就能印出true了

然而

SpringBoot並不推薦使用beans.xml方式作管理

而是使用配置類作管理

@Configuration:指明當前類別是一個配置類; 就是來替代之前的Spring配置文件

@Bean: 將方法的返回值添加到容器中; 容器中這個組件組件默認的id就是方法名

接下來我們產生一個config.MyAppConfig檔案如以下

@Configuration
public class MyAppConfig {

@Bean
public HelloService helloService(){
System.out.println("配置類@Bean給容器中添加組建了...");
return new HelloService();
}
}

然後並且把剛剛在SpringBootApplication類別上面的註解先註解掉

//@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringBoot02ConfigApplication {

public static void main(String[] args) {
SpringApplication.run(SpringBoot02ConfigApplication.class, args);
}

}

再來run一下我們的測試

@Test
public void testHelloService(){
boolean b= ioc.containsBean("helloService");
System.out.println(b);
}

這裡要注意"helloService"是對到helloService()方法

如果改成helloService02(), 那要用"helloService02"才找得到



沒有留言:

張貼留言

[leetcode] [KMP] KMP

ABCDABD... ABCDABF... 簡單的說, 傳統解兩字串匹配部分 可能會來個雙迴圈, 哀個比對, 當不匹配的時候, 會將下方列再後移1位 然後不匹配再後移 然而 如果像上放已經有4個屬於匹配的字串, 她就應該直接往後移四位來匹配, 而不是只移動1位 隱藏的思維是, 當...