【问题标题】:How to access a value defined in the application.properties file in Spring Boot如何在 Spring Boot 中访问 application.properties 文件中定义的值
【发布时间】:2015-08-12 05:48:28
【问题描述】:

我想访问application.properties 中提供的值,例如:

logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
logging.file=${HOME}/application.log

userBucket.path=${HOME}/bucket

我想在 Spring Boot 应用程序的主程序中访问 userBucket.path

【问题讨论】:

    标签: java spring-boot properties-file


    【解决方案1】:

    您可以使用以下方法访问 application.properties 文件值:

    @Value("${key_of_declared_value}")
    

    【讨论】:

      【解决方案2】:

      另一种在配置中查找键/值的方法。

      ...
      import org.springframework.core.env.ConfigurableEnvironment;
      ...
      @SpringBootApplication
      public class MyApplication {
      
          @Autowired
          private ConfigurableEnvironment  myEnv;
      
      ...
        
          @EventListener(ApplicationReadyEvent.class)
          public void doSomethingAfterStartup() 
          throws Exception {
              
              LOG.info("myEnv (userBucket.path): " + myEnv.getProperty("userBucket.path"));
          }
      } 
      

      【讨论】:

        【解决方案3】:

        最简单的方法是使用 Spring Boot 提供的 @Value 注解。您需要在类级别定义一个变量。例如:

        @Value("${userBucket.path}") 私有字符串 userBucketPath

        还有另一种方法可以通过环境类来做到这一点。例如:

        1. 将环境变量自动连接到您需要访问此属性的类:

        @Autowired 私有环境环境

        1. 使用环境变量在您需要的行中获取属性值:

        environment.getProperty("userBucket.path");

        希望这能回答你的问题!

        【讨论】:

          【解决方案4】:

          你可以使用@Value注解并访问spring bean中的属性

          @Value("${userBucket.path}")
          private String userBucketPath;
          

          【讨论】:

            【解决方案5】:

            @Value("${userBucket.path}") 私有字符串 userBucketPath;

            【讨论】:

            【解决方案6】:

            也许它可以帮助其他人: 你应该从import org.springframework.core.env.Environment;注入@Autowired private Environment env;

            然后以这种方式使用它: env.getProperty("yourPropertyNameInApplication.properties")

            【讨论】:

              【解决方案7】:

              application.yml 或 application.properties

              config.value1: 10
              config.value2: 20
              config.str: This is a simle str
              

              MyConfig 类

              @Configuration
              @ConfigurationProperties(prefix = "config")
              public class MyConfig {
                  int value1;
                  int value2;
                  String str;
              
                  public int getValue1() {
                      return value1;
                  }
              
                  // Add the rest of getters here...      
                  // Values are already mapped in this class. You can access them via getters.
              }
              

              任何想要访问配置值的类

              @Import(MyConfig.class)
              class MyClass {
                  private MyConfig myConfig;
              
                  @Autowired
                  public MyClass(MyConfig myConfig) {
                      this.myConfig = myConfig;
                      System.out.println( myConfig.getValue1() );
                  }
              }
              

              【讨论】:

                【解决方案8】:

                目前, 我知道以下三种方式:

                1. @Value注解

                    @Value("${<property.name>}")
                    private static final <datatype> PROPERTY_NAME;
                
                • 根据我的经验,在某些情况下您不是 能够获取该值或将其设置为null。 例如, 当您尝试在preConstruct() 方法或init() 方法中设置它时。 发生这种情况是因为值注入发生在类完全构造之后。 这就是为什么最好使用第 3 个选项的原因。

                2。 @PropertySource注解

                @PropertySource("classpath:application.properties")
                
                //env is an Environment variable
                env.getProperty(configKey);
                
                • PropertySouce 在加载类时将属性源文件中的值设置为 Environment 变量(在您的类中)。 因此,您可以轻松地获取后记。
                • 可通过系统环境变量访问。

                3. @ConfigurationProperties 注释。

                • 这主要用于 Spring 项目中加载配置属性。

                • 它根据属性数据初始化一个实体。

                • @ConfigurationProperties 标识要加载的属性文件。

                • @Configuration 根据配置文件变量创建一个 bean。

                  @ConfigurationProperties(prefix = "user")
                    @Configuration("用户数据")
                    类用户{
                      //属性和他们的getter/setter
                    }
                  
                    @自动连线
                    私人用户数据用户数据;
                  
                    userData.getPropertyName();

                【讨论】:

                • 如果默认位置被spring.config.location 覆盖怎么办? #2 还能用吗?
                • 在这种情况下,优先权就位。据我所知,当您使用命令行设置 spring.config.location 时,它具有高优先级,因此它会覆盖现有的。
                • 非常感谢 >> “根据我的经验,在某些情况下,您无法获取该值或将其设置为 null。例如,当您尝试在 preConstruct 中设置它时() 方法或 init() 方法。这是因为值注入发生在类完全构造之后。这就是为什么最好使用第 3 个选项的原因。"
                【解决方案9】:

                要从属性文件中选择值,我们可以有一个配置读取器类,例如 ApplicationConfigReader.class 然后根据属性定义所有变量。参考下面的例子,

                application.properties
                
                myapp.nationality: INDIAN
                myapp.gender: Male
                

                下面是对应的阅读器类。

                @Component
                @EnableConfigurationProperties
                @ConfigurationProperties(prefix = "myapp") 
                class AppConfigReader{
                    private String nationality;
                    private String gender
                
                    //getter & setter
                }
                

                现在我们可以在任何我们想要访问属性值的地方自动连接阅读器类。 例如

                @Service
                class ServiceImpl{
                    @Autowired
                    private AppConfigReader appConfigReader;
                
                    //...
                    //fetching values from config reader
                    String nationality = appConfigReader.getNationality() ; 
                    String gender = appConfigReader.getGender(); 
                }
                

                【讨论】:

                  【解决方案10】:

                  试过课程PropertiesLoaderUtils

                  这种方式不使用 Spring boot 的注解。传统的 Class 方式。

                  示例:

                  Resource resource = new ClassPathResource("/application.properties");
                      Properties props = PropertiesLoaderUtils.loadProperties(resource);
                      String url_server=props.getProperty("server_url");
                  

                  使用 getProperty() 方法传递键并访问属性文件中的值。

                  【讨论】:

                    【解决方案11】:

                    @Value Spring 注解用于将值注入 Spring-manged bean 中的字段,可以应用于字段或构造函数/方法参数级别。

                    例子

                    1. 字符串从注释到字段的值
                        @Value("string value identifire in property file")
                        private String stringValue;
                    
                    1. 我们也可以使用@Value注解来注入一个Map属性。

                      首先,我们需要在属性文件的{key: ‘value' } 表单中定义属性:

                       valuesMap={key1: '1', key2: '2', key3: '3'}
                    

                    并不是 Map 中的值必须用单引号引起来。

                    现在将属性文件中的这个值作为 Map 注入:

                       @Value("#{${valuesMap}}")
                       private Map<String, Integer> valuesMap;
                    

                    获取特定键的值

                       @Value("#{${valuesMap}.key1}")
                       private Integer valuesMapKey1;
                    
                    1. 我们也可以使用@Value注解来注入一个List属性。
                       @Value("#{'${listOfValues}'.split(',')}")
                       private List<String> valuesList;
                    

                    【讨论】:

                    • 对象呢?
                    【解决方案12】:

                    有两种方法可以访问 application.properties 文件中的值

                    1. 使用@Value 注释
                        @Value("${property-name}")
                        private data_type var_name;
                    
                    1. 使用环境类的实例
                    @Autowired
                    private Environment environment;
                    
                    //access this way in the method where it's required
                    
                    data_type var_name = environment.getProperty("property-name");
                    

                    您还可以使用构造函数注入或自己创建 bean 来注入环境实例

                    【讨论】:

                      【解决方案13】:

                      您可以使用 @Value 注释从 application.properties/yml 文件中读取值。

                      @Value("${application.name}")
                      private String applicationName;
                      

                      【讨论】:

                      • 表单你导入了哪个库值?
                      【解决方案14】:

                      您可以使用@Value("${property-name}") 从 application.properties 如果你的类被注释 @Configuration@Component

                      我尝试过的另一种方法是创建一个实用程序类以通过以下方式读取属性 -

                       protected PropertiesUtility () throws IOException {
                          properties = new Properties();
                          InputStream inputStream = 
                         getClass().getClassLoader().getResourceAsStream("application.properties");
                          properties.load(inputStream);
                      }
                      

                      您可以使用静态方法获取作为参数传递的键的值。

                      【讨论】:

                        【解决方案15】:

                        你可以使用@ConfigurationProperties,它很容易访问application.properties中定义的值

                        #datasource
                        app.datasource.first.jdbc-url=jdbc:mysql://x.x.x.x:3306/ovtools?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
                        app.datasource.first.username=
                        app.datasource.first.password=
                        app.datasource.first.driver-class-name=com.mysql.cj.jdbc.Driver
                        server.port=8686
                        spring.jpa.hibernate.ddl-auto=update
                        spring.jpa.generate-ddl=true
                        spring.jpa.show-sql=true
                        spring.jpa.database=mysql
                        

                        @Slf4j
                        @Configuration
                        public class DataSourceConfig {
                            @Bean(name = "tracenvDb")
                            @Primary
                            @ConfigurationProperties(prefix = "app.datasource.first")
                            public DataSource mysqlDataSourceanomalie() {
                                return DataSourceBuilder.create().build();
                            }
                        
                            @Bean(name = "JdbcTemplateenv")
                            public JdbcTemplate jdbcTemplateanomalie(@Qualifier("tracenvDb") DataSource datasourcetracenv) {
                                return new JdbcTemplate(datasourcetracenv);
                            }
                        

                        【讨论】:

                          【解决方案16】:

                          我也有这个问题。但是有一个非常简单的解决方案。只需在构造函数中声明变量即可。

                          我的例子:

                          application.properties:

                          #Session
                          session.timeout=15
                          

                          SessionServiceImpl 类:

                          private final int SESSION_TIMEOUT;
                          private final SessionRepository sessionRepository;
                          
                          @Autowired
                          public SessionServiceImpl(@Value("${session.timeout}") int sessionTimeout,
                                                    SessionRepository sessionRepository) {
                              this.SESSION_TIMEOUT = sessionTimeout;
                              this.sessionRepository = sessionRepository;
                          }
                          

                          【讨论】:

                            【解决方案17】:

                            应用程序可以从 application.properties 文件中读取 3 种类型的值。

                            application.properties


                                 my.name=kelly
                            
                            my.dbConnection ={connection_srting:'http://localhost:...',username:'benz',password:'pwd'}
                            

                            类文件

                            @Value("${my.name}")
                            private String name;
                            
                            @Value("#{${my.dbConnection}}")
                            private Map<String,String> dbValues;
                            

                            如果您在 application.properties 中没有属性,则可以使用默认值

                                    @Value("${your_name : default value}")
                                     private String msg; 
                            

                            【讨论】:

                              【解决方案18】:

                              另一种方法是将org.springframework.core.env.Environment 注入到您的 bean。

                              @Autowired
                              private Environment env;
                              ....
                              
                              public void method() {
                                  .....  
                                  String path = env.getProperty("userBucket.path");
                                  .....
                              }
                              

                              【讨论】:

                              • 当你需要访问的属性名称动态变化时也很有用
                              • 如果要搜索属性怎么办?我可以建议包括 import 语句,以便所有人都可以看到 Environment 包名称,可能是 org.springframework.core.env.Environment
                              • 注意不要导入错误的环境。我 intellij 自动导入了 CORBA 环境。
                              • 为什么我的环境是空的?
                              • @JanacMeena 遇到了 IntelliJ 自动导入 CORBA 的类而不是 org.springframework.core.env.Environment 的相同问题
                              【解决方案19】:

                              有两种方式,

                              1. 你可以在课堂上直接使用@Value
                                  @Value("#{'${application yml field name}'}")
                                  public String ymlField;
                              

                              1. 要使其干净,您可以清理 @Configuration 类,您可以在其中添加所有 @value
                              @Configuration
                              public class AppConfig {
                              
                                  @Value("#{'${application yml field name}'}")
                                  public String ymlField;
                              }
                              

                              【讨论】:

                                【解决方案20】:

                                按照以下步骤操作。 1:- 创建你的配置类,如下所示

                                import org.springframework.context.annotation.Bean;
                                import org.springframework.context.annotation.Configuration;
                                import org.springframework.beans.factory.annotation.Value;
                                
                                @Configuration
                                public class YourConfiguration{
                                
                                    // passing the key which you set in application.properties
                                    @Value("${userBucket.path}")
                                    private String userBucket;
                                
                                   // getting the value from that key which you set in application.properties
                                    @Bean
                                    public String getUserBucketPath() {
                                        return userBucket;
                                    }
                                }
                                

                                2:- 当你有一个配置类时,然后从你需要的配置中注入变量。

                                @Component
                                public class YourService {
                                
                                    @Autowired
                                    private String getUserBucketPath;
                                
                                    // now you have a value in getUserBucketPath varibale automatically.
                                }
                                

                                【讨论】:

                                  【解决方案21】:
                                  1.Injecting a property with the @Value annotation is straightforward:
                                  @Value( "${jdbc.url}" )
                                  private String jdbcUrl;
                                  
                                  2. we can obtain the value of a property using the Environment API
                                  
                                  @Autowired
                                  private Environment env;
                                  ...
                                  dataSource.setUrl(env.getProperty("jdbc.url"));
                                  

                                  【讨论】:

                                  • setUrl 是在哪里定义的?我怎么会得到一个编译器错误。实际上,如果可能的话,我对 setPassword 更感兴趣。谢谢。
                                  【解决方案22】:

                                  最好的办法是使用@Value注解,它会自动为你的对象private Environment en赋值。 这将减少您的代码,并且很容易过滤您的文件。

                                  【讨论】:

                                    【解决方案23】:

                                    获取属性值的最佳方法是使用。

                                    1.使用值注解

                                    @Value("${property.key}")
                                    private String propertyKeyVariable;
                                    

                                    2。使用环境 bean

                                    @Autowired
                                    private Environment env;
                                    
                                    public String getValue() {
                                        return env.getProperty("property.key");
                                    }
                                    
                                    public void display(){
                                      System.out.println("# Value : "+getValue);
                                    }
                                    

                                    【讨论】:

                                      【解决方案24】:

                                      对我来说,以上都没有直接对我有用。 我所做的如下:

                                      除了@Rodrigo Villalba Zayas 的回答,我还在课堂上添加了
                                      implements InitializingBean
                                      并实现了方法

                                      @Override
                                      public void afterPropertiesSet() {
                                          String path = env.getProperty("userBucket.path");
                                      }
                                      

                                      所以看起来像

                                      import org.springframework.core.env.Environment;
                                      public class xyz implements InitializingBean {
                                      
                                          @Autowired
                                          private Environment env;
                                          private String path;
                                      
                                          ....
                                      
                                          @Override
                                          public void afterPropertiesSet() {
                                              path = env.getProperty("userBucket.path");
                                          }
                                      
                                          public void method() {
                                              System.out.println("Path: " + path);
                                          }
                                      }
                                      

                                      【讨论】:

                                        【解决方案25】:

                                        @ConfigurationProperties 可用于将值从.properties(也支持.yml)映射到 POJO。

                                        考虑以下示例文件。

                                        .properties

                                        cust.data.employee.name=Sachin
                                        cust.data.employee.dept=Cricket
                                        

                                        Employee.java

                                        import org.springframework.boot.context.properties.ConfigurationProperties;
                                        import org.springframework.context.annotation.Configuration;
                                        
                                        @ConfigurationProperties(prefix = "cust.data.employee")
                                        @Configuration("employeeProperties")
                                        public class Employee {
                                        
                                            private String name;
                                            private String dept;
                                        
                                            //Getters and Setters go here
                                        }
                                        

                                        现在可以通过自动装配employeeProperties 访问属性值,如下所示。

                                        @Autowired
                                        private Employee employeeProperties;
                                        
                                        public void method() {
                                        
                                           String employeeName = employeeProperties.getName();
                                           String employeeDept = employeeProperties.getDept();
                                        
                                        }
                                        

                                        【讨论】:

                                        • 我使用这种方式并得到空返回,我将我的属性文件放在 src/test/resources 和属性 java 类(其中保存属性值)在 src/main/package/properties 中。我错过了什么?谢谢
                                        • 如果您不是在 Spring 测试中测试代码,则必须将文件保存到 src/main/resources
                                        • 与@AhmadLeoYudanto 相同,我无法改变这一点
                                        【解决方案26】:

                                        Spring-boot 允许我们提供多种方式来提供外部化配置,你可以尝试使用 application.yml 或 yaml 文件代替属性文件,并根据不同的环境提供不同的属性文件设置。

                                        我们可以将每个环境的属性分离到单独的spring配置文件下的单独的yml文件中。然后在部署期间您可以使用:

                                        java -jar -Drun.profiles=SpringProfileName
                                        

                                        指定要使用的弹簧配置文件。注意yml文件的名称应类似于

                                        application-{environmentName}.yml
                                        

                                        让它们被 springboot 自动占用。

                                        参考:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties

                                        从 application.yml 或属性文件中读取:

                                        从属性文件或yml中读取值的最简单方法是使用spring的@value注解。Spring会自动将yml中的所有值加载到spring环境中,所以我们可以直接使用来自环境的那些值,例如:

                                        @Component
                                        public class MySampleBean {
                                        
                                        @Value("${name}")
                                        private String sampleName;
                                        
                                        // ...
                                        
                                        }
                                        

                                        或者spring提供的另一种读取强类型bean的方法如下:

                                        YML
                                        
                                        ymca:
                                            remote-address: 192.168.1.1
                                            security:
                                                username: admin
                                        

                                        对应POJO读取yml:

                                        @ConfigurationProperties("ymca")
                                        public class YmcaProperties {
                                            private InetAddress remoteAddress;
                                            private final Security security = new Security();
                                            public boolean isEnabled() { ... }
                                            public void setEnabled(boolean enabled) { ... }
                                            public InetAddress getRemoteAddress() { ... }
                                            public void setRemoteAddress(InetAddress remoteAddress) { ... }
                                            public Security getSecurity() { ... }
                                            public static class Security {
                                                private String username;
                                                private String password;
                                                public String getUsername() { ... }
                                                public void setUsername(String username) { ... }
                                                public String getPassword() { ... }
                                                public void setPassword(String password) { ... }
                                            }
                                        }
                                        

                                        上述方法适用于 yml 文件。

                                        参考:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

                                        【讨论】:

                                          【解决方案27】:

                                          你也可以这样做......

                                          @Component
                                          @PropertySource("classpath:application.properties")
                                          public class ConfigProperties {
                                          
                                              @Autowired
                                              private Environment env;
                                          
                                              public String getConfigValue(String configKey){
                                                  return env.getProperty(configKey);
                                              }
                                          }
                                          

                                          然后无论你想从 application.properties 中读取什么,只需将 key 传递给 getConfigValue 方法即可。

                                          @Autowired
                                          ConfigProperties configProp;
                                          
                                          // Read server.port from app.prop
                                          String portNumber = configProp.getConfigValue("server.port"); 
                                          

                                          【讨论】:

                                          • Environment是什么包?
                                          • 在这里找到它:org.springframework.core.env.Environment
                                          • 如果默认位置被spring.config.location覆盖怎么办?
                                          【解决方案28】:

                                          如果您将在一个地方使用此值,您可以使用@Valueapplication.properties 加载变量,但如果您需要更集中的方式来加载此变量@ConfigurationProperties 是一种更好的方法。

                                          此外,如果您需要不同的数据类型来执行验证和业务逻辑,您可以加载变量并自动转换它。

                                          application.properties
                                          custom-app.enable-mocks = false
                                          
                                          @Value("${custom-app.enable-mocks}")
                                          private boolean enableMocks;
                                          

                                          【讨论】:

                                          • 选角非常好。无论我把它放在哪里,当我得到“这里不允许注释”时,还需要什么额外的东西。我错过了一些东西。我是否需要其他一些配置才能在任何地方使用此注释?
                                          【解决方案29】:

                                          您可以使用 @Value 注释并访问您正在使用的任何 Spring bean 中的属性

                                          @Value("${userBucket.path}")
                                          private String userBucketPath;
                                          

                                          Spring Boot 文档的 Externalized Configuration 部分解释了您可能需要的所有详细信息。

                                          【讨论】:

                                          • 作为另一种选择,也可以从 spring Environment 或通过 @ConfigurationProperties 获得这些
                                          • 要添加到@sodik 的答案之上,这是一个显示如何获取Environment stackoverflow.com/questions/28392231/… 的示例
                                          • 如果您需要访问超过 10 个值怎么办,您是否必须重复您的示例 10 次?
                                          • 一种方法是这样做,但它很麻烦。有基于@Configuration类的替代方法,问题在以下blog post中得到了很好的分析
                                          • 注意,这只适用于@Component(或其任何派生词,即@Repository等)
                                          猜你喜欢
                                          • 1970-01-01
                                          • 2020-12-25
                                          • 1970-01-01
                                          • 1970-01-01
                                          • 2021-07-10
                                          • 1970-01-01
                                          • 2017-11-16
                                          • 1970-01-01
                                          相关资源
                                          最近更新 更多