springBoot2.0以上Environment属性获取

SpringBoot2.0 获取Environment 环境变量中参数信息
如果当前对象在spring IOC 容器中,则可以直接使用 自动注入的当时从中获取Environment 中参数信息

  1. 使用方法: 用@Autowired方法即可获取当前项目中环境变量和配置文件属性, 或者还可以使用@Value 注解获取指定的配置属性参数
 @Autowired
 private Environment environment;
  1. 如果在普通POJO中获取环境变量中参数信息,可以还以选用构造器或者set 属性使用其属性,或者直接使用一下方式获取环境变量中的参数
    具体获取代码如下:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @author ccbobe
 */
@Component
public class EnvironmentUtils implements EnvironmentAware {

    private static Environment environment;

    @Override
    public void setEnvironment(Environment environment) {
        EnvironmentUtils.environment = environment;
    }
	// 获取环境变量中的配置属性
    public static String searchByKey(String key){
        return EnvironmentUtils.environment.getProperty(key);
    }
}

请注意,此方法在spring bean 初始化的时候使用无效,注入异常

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot启动类中,可以通过在类上添加注解`@SpringBootApplication`来启用Spring Boot应用程序。获取Environment对象的方式有以下两种: 1. 使用@Autowired注解将Environment对象注入到启动类中: ```java @SpringBootApplication public class DemoApplication { @Autowired private Environment env; public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @PostConstruct public void init() { String url = env.getProperty("spring.datasource.url"); // TODO: do something with url } } ``` 在上面的代码中,我们在启动类中定义了一个Environment类型的成员变量,并使用@Autowired注解将其注入到启动类中。在init()方法中,我们使用getProperty()方法获取了配置文件中的spring.datasource.url配置信息。 2. 使用CommandLineRunner回调函数获取Environment对象: ```java @SpringBootApplication public class DemoApplication implements CommandLineRunner { private Environment env; public DemoApplication(Environment env) { this.env = env; } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Override public void run(String... args) throws Exception { String url = env.getProperty("spring.datasource.url"); // TODO: do something with url } } ``` 在上面的代码中,我们在启动类中实现了CommandLineRunner接口,并在构造函数中注入了Environment对象。在run()方法中,我们使用getProperty()方法获取了配置文件中的spring.datasource.url配置信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值