JAVA spring boot 微服务快速上手(03)

4 篇文章 0 订阅
3 篇文章 0 订阅
本节内容主要介绍如何使用配置文件的属性给实体类赋值。1. 通过Controller类直接读取配置文件给实体类赋值可采用两种方式,一种是直接在application.yml文件里配置属性:my: name: hawk age: 30之后在Controller里(即被@RestController修饰的类里)在需要关联的变量前用@Value("${属性名}")修饰即可。@Value...
摘要由CSDN通过智能技术生成

本节内容主要介绍如何使用配置文件的属性给实体类赋值。

1. 通过Controller类直接读取配置文件

给实体类赋值可采用两种方式,一种是直接在application.yml文件里配置属性:

my:
  name: hawk
  age: 30

之后在Controller里(即被@RestController修饰的类里)在需要关联的变量前用@Value("${属性名}")修饰即可。

@Value("${my.name}")
private String myName;
@Value("${my.age}")
private String myAge;

2. 通过Controller类读取JavaBean

但更常见的做法是使用JavaBean类。在介绍JavaBean类的使用前,我们先介绍下如何使用多个配置文件。
为了实现控制诸如开发、测试、生产环境,我们可以使用不同的配置文件,例如用一个application.yml,和多个application-{环境名}.yml。在application.yml里指定了使用哪套环境:

  • application.yml
    - application-dev.yml
    - application-test.yml
    - application-prod.yml

2.1 在application.yml里配置:

spring:
  profiles:
    active: dev

active指定使用dev环境,后续会自动读取application-dev.yml的数据。

2.2 在application-dev.yml里配置数据:

server:
  port: 8889
logging:
  #日志存储地址
  file: logs/config/demo-xx.log
info:
  name : demo
my:
  name: hawk
  age: 30
  number: ${random.int}
  uuid: ${random.uuid}
  messages: ${random.long(9999)}
  value: ${random.value}
  greeting: Hi, I'm ${my.name}, you are watching developing page! And here the age

port指定了开发环境使用8889端口,日志存储路径为工程根目录下:logs/config/demo-xx.log,${random.int}说明number是整型随机数。其他类似,可从变量名定义类型看出具体数值格式。

2.3 创建ConfigBean:

在HelloWorldApplication.java同级目录下创建ConfigBean.java:

package com.hawkeye.helloworld;

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

@ConfigurationProperties(prefix = "my")
@Component
public class ConfigBean {
    private String name;
    private int age;
    private int number;
    private String uuid;
    private long messages;
    private String value;
    private String greeting;

    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return this.name;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getAge() {
        return this.age;
    }
    public void setNumber(int number) {
        this.number = number;
    }
    public int getNumber() {
        return this.number;
    }
    public void setUuid(String uuid) {
        this.uuid = uuid;
    }
    public String getUuid() {
        return this.uuid;
    }
    public void setMessages(long max) {
        this.messages = max;
    }
    public long getMessages() {
        return this.messages;
    }
    public void setValue(String value) {
        this.value = value;
    }
    public String getValue() {
        return this.value;
    }
    public void setGreeting(String greeting) {
        this.greeting = greeting;
    }
    public String getGreeting() {
        return this.greeting;
    }
}

注解@ConfigurationProperties说明ConfigBean是配置属性类,使用prefix为“my”,对应到application-dev.yml的my字段。

2.4 修改HelloWorldApplication类

增加@EnableConfigurationProperties({ConfigBean.class}),说明使用了ConfigBean配置类:

@SpringBootApplication
@RestController
@EnableConfigurationProperties({ConfigBean.class})
public class HelloWorldApplication {

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

    @GetMapping("/hi")
    public String hi() {
        return "hi, this is hawk's program";
    }

    @Autowired
    ConfigBean configBean;
    @RequestMapping(value = "/greeting")
    public String greeting() {
        return configBean.getGreeting() + "<br/>" +
                configBean.getAge() + "<br/>" +
                configBean.getUuid() + "<br/>" +
                configBean.getMessages();

2.5 执行效果:

greeting

3. 使用自定义配置

当数据量非常多时,不可能把所有配置都放在application中,毕竟这是主要用于系统控制的。
此时,可以重新定义配置文件,并在JavaBean类中,指定使用该文件。

3.1 生成自定义配置文件

先在resources文件夹下定义hello-world.properties文件,内容如下:

com.hawkeye.petname=sharp
com.hawkeye.pet=doge

3.2 定义JavaBean读取自定义配置

在HelloWorldApplication.java同级目录下创建Favorites.java文件:

package com.hawkeye.helloworld;


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@ConfigurationProperties(prefix = "com.hawkeye")
@Configuration
@PropertySource(value = "classpath:hello-world.properties")
public class Favorites {
    private String petname;
    private String pet;

    public void setPetname(String petname) {
        this.petname = petname;
    }
    public String getPetname() {
        return this.petname;
    }
    public void setPet(String pet) {
        this.pet = pet;
    }
    public String getPet() {
        return this.pet;
    }
}

通过@ConfigurationProperties,@Configuration,@PropertySource三个注解指明Favorites类是配置类,且可以读取前缀为com.hawkeye,路径为跟application.yml同级的配置文件:hello-world.properties。

3.3 再次修改HelloWorldApplication类:

@EnableConfigurationProperties修饰中,也要添加Favorites.class。
最终完整版的HelloWorldApplication类如下:

package com.hawkeye.helloworld;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@SpringBootApplication
@RestController
@EnableConfigurationProperties({ConfigBean.class, Favorites.class})
public class HelloWorldApplication {

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

    @GetMapping("/hi")
    public String hi() {
        return "hi, this is hawk's program";
    }

    @Autowired
    ConfigBean configBean;
    @RequestMapping(value = "/greeting")
    public String greeting() {
        return configBean.getGreeting() + "<br/>" +
                configBean.getAge() + "<br/>" +
                configBean.getUuid() + "<br/>" +
                configBean.getMessages();
    }

    @Autowired
    Favorites favorites;
    @RequestMapping(value = "/favor")
    public String favor() {
        return favorites.getPetname() + ": " +
                favorites.getPet();
    }
}

3.4 执行效果:

favor

4. 其他配置文件如下:

\resources\application-test.yml

server:
  port: 8890
logging:
  #日志存储地址
  file: logs/config/demo-xx.log
info:
  name : demo
my:
  name: hawk
  age: 30
  number: ${random.int}
  uuid: ${random.uuid}
  messages: ${random.long(9999)}
  value: ${random.value}
  greeting: Hi, I'm ${my.name}, you are watching test page! And here the age

\resources\application-prod.yml

server:
  port: 8891
logging:
  #日志存储地址
  file: logs/config/demo-xx.log
info:
  name : demo
my:
  name: hawk
  age: 30
  number: ${random.int}
  uuid: ${random.uuid}
  messages: ${random.long(9999)}
  value: ${random.value}
  greeting: Hi, I'm ${my.name}, you are watching product page! And here the age

5. 整体工程结构:

project

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值