首页 > 技术文章 > springboot 自定义属性

whx7762 2017-12-07 09:55 原文

前言

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})注解。

 

推荐阅读