Implementation of attribute assignment operation in SpringBoot

Note: When there are frequently changing data in the program, if you modify it in the way you think and compile and package it, it will cause the code to be highly coupled and not easy to maintain! So can you assign values ​​to attributes dynamically?

Property fixed value

//动态获取ip和端口数据
/**
 * @responseBody
 * 注解作用:
 *   1.将对象转化成Json格式,
 *   2.如果返回值是String类型,则返回字符串本身
 *   3.一般客户端发起ajax请求时,采用该注解返回数据,将不会执行视图解析器操作
 */
@RestController
public class RedisController{
  private String host="192.168.126.112";
  private Integer port=6379;
  public String getMsg(){
    return host+":"+port;
  }
}

Dynamically obtain ip and port data
About YML file description

#YML文件语法:
 # 1.key:(空格) value 注意:value前面有个空格
 # 2.key与key之间有层级的缩进关系
server:
 port: 8090
 #属性赋值操作,编辑属性时注意前缀,只要springboot启动,该数据就会被写入内存中,key-value格式
redis:
  host: 192.168.126.130
  port: 6379

Assignment operations to attributes

public class RedisController {

  @Value("${redis.host}") //spel表达式
  private String host;  // = "192.168.126.130";   private String host;  // = "192.168.126.130";
  @Value("${redis.port}")
  private Integer port;  // = 6379;

  @RequestMapping("/getMsg")
  public String getMsg(){

    return host + ":" + port;
  }
}

Specify the configuration file to assign values ​​to the attributes

Note: Since the data in the YML configuration file is generally system-level data, the general business data will be written to the peoperties configuration file.

Edit RedisController

@RestController
//动态导入pro配置文件,交给spring容器进行加载
@PropertySource("classpath:/properties/redis.properties")
public class RedisController {
  //通过YML给属性赋值
 @Value("${redis.host}")//sple表达式
 private String host;
  @Value("${redis.port}")
  private Integer port;
  @RequestMapping("/getMsg")
  public String getMsg(){
    return host+":"+port;
  }
  /*由于YML配置文件中的数据一般都是系统级别的数据,所以一般的业务数据
 都会写到peoperties配置文件中*/
 //通过properties给属性赋值
 @Value("${pro.redis.host}")
  private String prohost;
  @Value("${pro.redis.port}")
  private Integer proport;
  @RequestMapping("/getpro")
  public String getpro(){
    return prohost+":"+proport;
  }
}

Some high-frequency interview questions collected in the latest 2020 (all organized into documents), there are many dry goods, including mysql, netty, spring, thread, spring cloud, jvm, source code, algorithm and other detailed explanations, as well as detailed learning plans, interviews Question sorting, etc. For those who need to obtain these contents, please add Q like: 11604713672

Guess you like

Origin blog.csdn.net/weixin_51495453/article/details/113201604