Spring Boot从入门到放弃-获取自定义配置

摘要:

      通过Spring注解获取配置文件中配置的全局变量。使用配置文件方便集中管理所有的配置。可以通过 @Value("${book.author}")获取,或者通过@ConfigurationProperties(prefix = "book"),属性名和配置名需要相同,但需要设置set和get方法。

Value案例:

application.properties 文件:

book.author = tom
book.name = Springboot
BookController.java文件:
package com.edu.usts.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@EnableAutoConfiguration
@Controller
public class BookController {
//  取自定义属性值
    @Value("${book.author}")
    private String author;

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

    @ResponseBody
    @RequestMapping("/bookinfo")
    public String showinfo(){
        return author+":"+name;
    }

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


}

页面显示:

成功获取配置文件中自定义数据。不要和预留关键字冲突。

ConfigurationProperties案例:

application.properties 文件不变。

BookController.java:

package com.edu.usts.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@EnableAutoConfiguration
@Controller
@ConfigurationProperties(prefix = "book")
public class BookController {


//  取自定义属性值
    private String author;

    private String name;

//    使用 ConfigurationProperties 开头,需要设置set、get方法
    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @ResponseBody
    @RequestMapping("/bookinfo")
    public String showinfo(){
        return author+":"+name;
    }

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


}

注: 使用@Value注入每个自定义配置在项目中显得很麻烦,数据量一大就难受了。Spring Boot提供了基于类型安全的配置方式即@ConfigurationProperties方式配置,将application.properties中的属性和一个Bean的属性关联。从而实现类型安全的配置。

源码gitee地址:

https://gitee.com/jockhome/springboot

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值