Java 之 Spring Boot 配置

寫在前面:關於Spring Boot的hello word  網上一堆,所以這裏並不是從hello world  起步,而是 從配置application.properties開始,畢竟一個項目開始,首先就要配置好數據庫。

一、目錄結構

可以看到,目前我配置了兩個properties,這樣也比較貼合實際需求,不可能把所有的配置全放application.properties中。

二、 安裝依賴。

1、爲了每個Bean不用寫setter和getter,安裝lombok

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
    <optional>true</optional>
</dependency>

安裝後,在需要的Bean上面就可以使用@Data,然後就不用收些getter和setter了。

2、configuration-processor,這個是在使用出了application.properties時,指定文件路徑的時候使用

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

三、使用

我想在TestController中使用application.properties 和 test.properties這兩個配置文件。

1、先看看test.properties中的內容:

創建一個TestBean:

package com.dany.blog.bean;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component  -->跟Spring Boot說:我這裏有個組件
@Configuration  -->是配置文件
@Data           -->不用自己寫setter和getter了
@ConfigurationProperties(prefix = "test") -->剛纔的那個test.properties中 內容中 前綴爲test的。
@PropertySource("classpath:test.properties") -->指定這個配置在哪裏
public class TestBean {
    private String level;
    private String name;
}

2、看看application.properties中的內容:

同樣創建一個blogProperties的Bean,這個內容就比上面的那個少很多@了,因爲SpringBoot默認就是找application.properties

 

package com.dany.blog.bean;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Data
@Component
public class BlogProperties {

    @Value("${dany.blog.name}")
    private String name;


    @Value("${dany.blog.title}")
    private String title;
}

3、在TestControoler中使用

package com.dany.blog.controller;


import com.dany.blog.bean.BlogProperties;
import com.dany.blog.bean.TestBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private TestBean testBean;

    @Autowired
    private BlogProperties blogProperties;

    @RequestMapping("/")
    public String index() {
        return "test name:"+testBean.getName()+"    blog的配置"+blogProperties.getName();
    }


}

4、結果

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章