Spring Boot @ConfigurationPropreties 实例

Spring Boot @ConfigurationProperties是让开发人员比较容易地将整个文件映射成一个对象。

1. 简单属性文件

通常,我们使用@Value注释来逐个注入.properties值,这对于小而简单的结构.properties文件很有用。

文件:global.properties

email=test@yiibai.com
thread-pool=12

@Value 示例
文件:GlobalProperties.java

@Component
@PropertySource("classpath:global.properties")
public class GlobalProperties {

    @Value("${thread-pool}")
    private int threadPool;

    @Value("${email}")
    private String email;

    //getters and setters

}

@ConfigurationProperties实例

文件:GlobalProperties.java

import org.springframework.boot.context.properties.ConfigurationProperties;

@Component
@PropertySource("classpath:global.properties")
@ConfigurationProperties
public class GlobalProperties {

    private int threadPool;
    private String email;

    //getters and setters

}

2.复杂属性文件

2.1. 查看复杂的结构.properties文件,如何通过@Value注释映射值。

文件:application.properties

#Logging
logging.level.org.springframework.web=ERROR
logging.level.com.yiibai=DEBUG

#Global
email=test@yiibai.com
thread-pool=10

#App
app.menus[0].title=Home
app.menus[0].name=Home
app.menus[0].path=/
app.menus[1].title=Login
app.menus[1].name=Login
app.menus[1].path=/login

app.compiler.timeout=5
app.compiler.output-folder=/temp/

app.error=/error/

或YAML中的下面配置, 文件: application.yml

logging:
  level:
    org.springframework.web: ERROR
    com.yiibai: DEBUG
email: test@yiibai.com
thread-pool: 10
app:
  menus:
    - title: Home
      name: Home
      path: /
    - title: Login
      name: Login
      path: /login
  compiler:
    timeout: 5
    output-folder: /temp/
  error: /error/

 
 
YAML

注意:@ConfigurationProperties支持.properties.yml文件。

下面可使用@ConfigurationProperties来配置完成,创建一个@ConfigurationProperties bean,如下所示:

文件: AppProperties.java -

package com.yiibai;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@ConfigurationProperties("app") // prefix app, find app.* values
public class AppProperties {

    private String error;
    private List<Menu> menus = new ArrayList<>();
    private Compiler compiler = new Compiler();

    public static class Menu {
        private String name;
        private String path;
        private String title;

        //getters and setters

        @Override
        public String toString() {
            return "Menu{" +
                    "name='" + name + '\'' +
                    ", path='" + path + '\'' +
                    ", title='" + title + '\'' +
                    '}';
        }
    }

    public static class Compiler {
        private String timeout;
        private String outputFolder;

        //getters and setters

        @Override
        public String toString() {
            return "Compiler{" +
                    "timeout='" + timeout + '\'' +
                    ", outputFolder='" + outputFolder + '\'' +
                    '}';
        }

    }

    //getters and setters
}

文件:GlobalProperties.java -

package com.yiibai;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties // no prefix, find root level values.
public class GlobalProperties {

    private int threadPool;
    private String email;

    //getters and setters
}

3. 演示实例

测试以确保.properties值正确映射到对象。文件:WelcomeController.java 

package com.yiibai;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

@Controller
public class WelcomeController {

    private static final Logger logger = LoggerFactory.getLogger(WelcomeController.class);

    private AppProperties app;
    private GlobalProperties global;

    @Autowired
    public void setApp(AppProperties app) {
        this.app = app;
    }

    @Autowired
    public void setGlobal(GlobalProperties global) {
        this.global = global;
    }

    @RequestMapping("/")
    public String welcome(Map<String, Object> model) {

        String appProperties = app.toString();
        String globalProperties = global.toString();

        logger.debug("Welcome {}, {}", app, global);

        model.put("message", appProperties + globalProperties);
        return "welcome";
    }

}

文件:SpringBootWebApplication.java -

package com.yiibai;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootWebApplication {

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

}

使用Maven命令mvn spring-boot:run启动Spring Boot,运行成功后访问默认/控制器,查看控制台输出:

Welcome
    AppProperties{error='/error/',
        menus=[
            Menu{name='Home', path='/', title='Home'},
            Menu{name='Login', path='/login', title='Login'}
        ],
        compiler=Compiler{timeout='5', outputFolder='/temp/'}},

    GlobalProperties{threadPool=10, email='test@yiibai.com'}

 
 
Shell

@ConfigurationProperties验证

让这个@ConfigurationProperties支持JSR-303 bean验证 -javax.validation

文件:GlobalProperties.java -

package com.yiibai;

import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

@Component
@ConfigurationProperties
public class GlobalProperties {

    @Max(5)
    @Min(0)
    private int threadPool;

    @NotEmpty
    private String email;

    //getters and setters
}

尝试再次使用Maven命令mvn spring-boot:run启动Spring Boot,并查看控制台:


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值