springboot获取值

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

springboot获取值

一粒程序米   2022-06-03 我要评论

在项目中,很多时候需要用到一些配置信息,这些信息在测试环境和生产环境下可能会有不同的配置,后面根据实际业务情况有可能还需要再做修改。我们不能将这些配置在代码中写死,最好是写到配置文件中,比如可以把这些信息写到 application.yml 文件中。

那么,怎么在代码里获取或者使用这个地址呢?有2个方法。

方法一:

我们可以通过@Value 注解的 ${key} 即可获取配置文件(application.yml)中和 key 对应的 value 值,这个方法适用于微服务比较少的情形

方法二:

在实际项目中,遇到业务繁琐,逻辑复杂的情况,需要考虑封装一个或多个配置类。例如,假如在当前服务中,某个业务需要同时调用微服务1、微服务2和微服务3。

如果这样一个个去使用 @Value 注解引入相应的微服务地址的话,太过于繁琐。

也许实际业务中,远远不止这三个微服务,甚至十几个都有可能。对于这种情况,我们可以先定义一个 MicroServiceUrl 类来专门保存微服务的 URL

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "url")
public class MicroServiceUrl {
private String orderUrl;
private String userUrl;
private String shoppingUrl;
public String getOrderUrl() {
return orderUrl;
}
public void setOrderUrl(String orderUrl) {
this.orderUrl = orderUrl;
}
public String getUserUrl() {
return userUrl;
}
public void setUserUrl(String userUrl) {
this.userUrl = userUrl;
}
public String getShoppingUrl() {
return shoppingUrl;
}
public void setShoppingUrl(String shoppingUrl) {
this.shoppingUrl = shoppingUrl;
}
}

添加依赖:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

目前配置写好了,此时,不需要在代码中一个个引入这些微服务的 URL,直接通过 @Resource 注解将刚刚写好的配置类注入进来即可使用了,以下是测试Controller:

import com.example.test1.config.MicroServiceUrl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* 获取配置文件(application.yml)中和 key 对应的 value 值
* 2种方法
*/
@RestController
@RequestMapping("/test")
public class ConfigController {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigController.class);
@Value("${url.orderUrl}")
private String orderUrl;
@Resource
private MicroServiceUrl microServiceUrl;
@RequestMapping("/config")
public String testConfig() {
LOGGER.info("获取的地址为:{}", orderUrl);
LOGGER.info("微服务1地址为:{}", microServiceUrl.getOrderUrl());
LOGGER.info("微服务2地址为:{}", microServiceUrl.getUserUrl());
LOGGER.info("微服务3地址为:{}", microServiceUrl.getShoppingUrl());
return "success";
}
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们