碼雲地址:
https://gitee.com/dream_fcy/elveos/tree/dev/ dev分支;
構建軟件
IDEA
環境
JDK1.8
開始
本項目的構建採用屬性文件的方式,ymi配置暫不涉及
1.application.properties 屬性文件及按環境加載配置
1.屬性配置文件的位置
spring會從classpath下的/config目錄或者classpath的根目錄查找application.properties或application.yml。/config優先於classpath根目錄
2.springboot自定義屬性,需要構建對應的javabean來進行配置注入,這種方式,本項目不採用,此次我們採用屬性工具類的方式進行。
擴展:自定義方式:
application.properties 添加
my1.age=21
my1.name=HOWD
創建javabean
@Component
@ConfigurationProperties(prefix = "my1")
public class demoProperties {
private int age;
private String name;
// 省略 get set
}
需要添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2.多環境化配置
在開發中,會有多個環境,不同環境連接不同的數據庫,這個時候就需要spring.profile.active,它的格式爲application-{profile}.properties,這裏的 application 爲前綴不能改,{profile}是我們自己定義的。在resource路徑下創建三個.properties後綴的文件。如:
- application-dev.properties
- application-test.properties
- application-prod.properties
在application.properties 文件中添加
spring.profile.active=dev
則在加載完application.properties後會再去加載application-dev.properties 文件中的屬性
說明:公共配置放到application.properties 屬性中,差異化的配置放到各個環境中
3.自定義屬性工具類
類地址,參見碼雲:com.elves.fcy.elvecores.base.untils.props.PropSutils
在項目portal 中創建 ProtalAppcalication,代碼如下:
@SpringBootApplication
public class ProtalAppcalication extends ElvesBootApplication {
public static void main(String[] args) {
SpringApplication.run(ProtalAppcalication.class, args);
}
}
爲何要繼承ElvesBootApplication ,ElvesBootApplication 中定義了一些公共配置,爲項目以來準備
在ProtalAppcalication 添加bean
/*配置屬性文件地址*/
@Bean("elvesPropsResources")
@Qualifier("elvesPropsResources")
public Resource[] elvesPropsResources() {
ClassPathResource[] cres = new ClassPathResource[1];
cres[0] = new ClassPathResource("");
return cres;
}
/*對屬性文件中加密的配置進行解密*/
@Bean("elvesPropsDecryptProperties")
@Qualifier("elvesPropsDecryptProperties")
public List<String> elvesPropsDecryptProperties() {
List<String> des = new ArrayList<String>();
return des;
}
在ElvesBootApplication 中添加工具類
@Bean("elvesPropSutils")
@Qualifier("elvesPropSutils")
public PropSutils elvesPropSutils(
@Qualifier("elvesPropsResources") Resource[] res,
@Qualifier("elvesPropsDecryptProperties") List<String> des) {
return new PropSutils(res, des);
}
注意:工具中使用到了
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.16</version>
</dependency>
4.隨機數屬性
Spring Boot 的屬性配置文件中 ${random} 可以用來生成各種不同類型的隨機值,從而簡化了代碼生成的麻煩,例如 生成 int 值、long 值或者 string 字符串。
32位隨機字符串
rand.str = ${random.value}
隨機int類型
rand.intid = ${random.int}
隨機long類型
rand.longid = ${random.long}
100以內的隨機int類型
rand.number = ${random.int(100)}
0-100範圍內的隨機int類型
rand.range = ${random.int[0,100]}
5.修改banner.txt,自定義項目啓動
在resource下創建 banner.txt 文件
圖案製作網址 http://patorjk.com/software/taag
如果你要放.jpg .gif 格式也可以
只要在properties配置文件中 加上
spring.banner.image.location=banner/xxx.jpg