1. 程式人生 > >springboot 自定義屬性

springboot 自定義屬性

artifact 正常 進行 fix framework 美的 是我 setter autowire

前言

spring boot使用application.properties默認了很多配置。但需要自己添加一些配置的時候,我們如何添加呢

1.添加自定義屬性

在src/main/resources/application.properties:加入:

#自定義屬性.

com.whx.blog.name= whx

com.whx.blog.title=Spring Boot教程 

2 方式一 @Value

然後通過@Value("${屬性名}")註解來加載對應的配置屬性,具體如下:

(以下這種方式已經過時了,不推薦使用,但能正常運行的)。

@Component
public class BlogProperties {
   
    @Value(
"${com.whx.blog.name}") private String name;//博客作者 @Value("${com.whx.blog.title}") private String title;//博客標題 // 省略getter和setter }

通過單元測試來驗證BlogProperties中的屬性是否已經根據配置文件加載了。

引入單元測試依賴:

<!-- spring boot 單元測試. -->
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
       </dependency>

進行編碼進行單元測試:

package com.kfit;
 
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.kfit.properties.BlogProperties; /** * * @author * @version v.0.1 */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(App.class) public class AppTest{ @Autowired private BlogProperties blogProperties; @Test public void testBlog() throws Exception { System.out.println("AppTest.testBlog()="+blogProperties); Assert.assertEquals("Angel",blogProperties.getName()); Assert.assertEquals("Spring Boot教程", blogProperties.getTitle()); } }

運行單元測試,完美的看到我們想要的結果了,但是我們剛剛提到了BlogProperties寫法已經不推薦使用了,那麽怎麽寫會比較perfect呢?

3.方式二 @ConfigurationProperties

看如下優雅的編碼風格:

先引入spring boot提供的一個配置依賴:

<!--spring boot 配置處理器 -->      
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-configuration-processor</artifactId>
           <optional>true</optional>
        </dependency>

在這裏我們主要使用@ConfigurationProperties註解進行編碼

當我們有很多配置屬性的時候,我們會把這些屬性作為字段建立一個javabean,並將屬性值賦予他們。

建立javabean為BlogProperties:

/**
 * prefix="com.whx.blog" :
 *
 * 在application.properties配置的屬性前綴,
 *
 * 在類中的屬性就不用使用{@value}進行註入了。
 *
 * @author whx
 * @version v.0.1
 */
@ConfigurationProperties(prefix="com.whx.blog")
public class BlogProperties {
   
    private String name;//博客作者
   
    private String title;//博客標題
 
    // 省略getter和setter
}

需要加個註解@ConfigurationProperties,並加上它的prefix。

另外需要在應用類或者application類,加EnableConfigurationProperties({BlogProperties.class})註解。

springboot 自定義屬性