您的位置:首页 > 教育 > 培训 > SpringBoot配置参数获取

SpringBoot配置参数获取

2024/10/6 10:41:37 来源:https://blog.csdn.net/Pluto_CSND/article/details/140012534  浏览:    关键词:SpringBoot配置参数获取

1、使用@Value注解

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;@Component
public class MyBean {@Value("${myapp.name}") private String appName;public void printAppName() {System.out.println(appName);}
}

2、使用Environment对象

import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;@Component
public class MyBean {private final Environment environment;public MyBean(Environment environment) {this.environment = environment;}public void printConfigParam() {String paramValue = environment.getProperty("myapp.param"); System.out.println(paramValue);}
}

3、使用@ConfigurationProperties 注解

当有大量的配置参数时,可以将它们组合到一个POJO类中,并使用@ConfigurationProperties注解进行自动装配。

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix = "myapp") // myapp 为配置参数的前缀
public class ConfigEntity {private String name;private String param;private int version;// getters and setters...public static class InnerClass {private boolean enabled;// getter and setter for inner class properties...}private InnerClass inner;// getters and setters for inner class properties...
}

4、使用@EnableConfigurationProperties 注解

如果想要全局共享配置参数,则可以使用@EnableConfigurationProperties注解。首先创建一个与配置项对应的POJO类,并使用@ConfigurationProperties 注解指定前缀。然后,在主程序类上添加@EnableConfigurationProperties注解,并传入该POJO类作为参数。示例如下所示:

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;@SpringBootApplication
@EnableConfigurationProperties(ConfigEntity.class)
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com