如何访问Spring Boot中application.properties文件中定义的值

Qas*_*sim 265 java properties-file spring-boot

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

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

userBucket.path=${HOME}/bucket
Run Code Online (Sandbox Code Playgroud)

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

Mas*_*ave 388

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

@Value("${userBucket.path}")
private String userBucketPath;
Run Code Online (Sandbox Code Playgroud)

Spring Boot文档的Externalized Configuration部分解释了您可能需要的所有细节.

  • 请注意,这仅适用于“@Component”(或其任何衍生物,即“@Repository”等) (8认同)
  • 作为另一种选择,我们也可以从春季`环境`或通过`@ConfigurationProperties`获得 (4认同)
  • 要添加@ sodik的答案,这是一个示例,说明如何获取[环境](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env /Environment.html)http://stackoverflow.com/questions/28392231/how-to-determine-programmatically-the-current-active-profile-using-spring-boot (3认同)

Rod*_*yas 190

另一种方法是向您的bean注入Environment.

@Autowired
private Environment env;
....

public void method() {
    .....  
    String path = env.getProperty("userBucket.path");
    .....
}
Run Code Online (Sandbox Code Playgroud)

  • 当您需要访问的属性的名称动态更改时,此选项也很有用 (5认同)
  • 如果要搜索属性怎么办?我可以建议包含import语句,这样所有人都可以看到环境包名称,可能是org.springframework.core.env.Environment (3认同)
  • 为什么我的env为null? (3认同)
  • 注意不要导入错误的环境。我intellij自动导入了CORBA环境。 (2认同)
  • @JanacMeena有同样的问题IntelliJ自动导入CORBA的类而不是`org.springframework.core.env.Environment` (2认同)

Job*_*eph 23

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

请考虑以下示例文件.

的.properties

cust.data.employee.name=Sachin
cust.data.employee.dept=Cricket
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

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

@Autowired
private Employee employeeProperties;

public void method() {

   String employeeName = employeeProperties.getName();
   String employeeDept = employeeProperties.getDept();

}
Run Code Online (Sandbox Code Playgroud)

  • 我使用这种方式并得到 null 返回,我将属性文件放在 src/test/resources 中,将属性 java 类(其中保存属性值)放在 src/main/package/properties 中。我错过了什么?谢谢 (2认同)

Dhw*_*tel 18

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

1.@Value注释

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

2.@PropertySource注释

@PropertySource("classpath:application.properties")

//env is an Environment variable
env.getProperty(configKey);
Run Code Online (Sandbox Code Playgroud)
  • PropertySouceEnvironment加载类时,将属性源文件中的值设置在变量(在您的类中)中。因此,您可以轻松获取后记。
  • 可通过系统环境变量访问。

3.@ConfigurationProperties注释。

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

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

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

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

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

  • 非常感谢&gt;&gt;“根据我的经验,在某些情况下您无法获取该值或将其设置为 null。例如,当您尝试在 preConstruct() 方法或 init() 中设置它时方法。发生这种情况是因为值注入发生在类完全构造之后。这就是为什么最好使用第三个选项。"&lt;&lt; (3认同)

luc*_*fer 12

你也可以用这种方式......

@Component
@PropertySource("classpath:application.properties")
public class ConfigProperties {

    @Autowired
    private Environment env;

    public String getConfigValue(String configKey){
        return env.getProperty(configKey);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,无论您想从 application.properties 读取的任何内容,只需将键传递给 getConfigValue 方法即可。

@Autowired
ConfigProperties configProp;

// Read server.port from app.prop
String portNumber = configProp.getConfigValue("server.port"); 
Run Code Online (Sandbox Code Playgroud)

  • “Environment”是什么包? (2认同)

小智 7

按着这些次序。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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

@Component
public class YourService {

    @Autowired
    private String getUserBucketPath;

    // now you have a value in getUserBucketPath varibale automatically.
}
Run Code Online (Sandbox Code Playgroud)


Aka*_*rma 7

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

application.properties

myapp.nationality: INDIAN
myapp.gender: Male
Run Code Online (Sandbox Code Playgroud)

下面是相应的读者类。

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "myapp")
class AppConfigReader{
    private String nationality;
    private String gender

    // Getter and setter
}
Run Code Online (Sandbox Code Playgroud)

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

例如,

@Service
class ServiceImpl{
    @Autowired
    private AppConfigReader appConfigReader;

    //...
    // Fetching values from the configuration reader
    String nationality = appConfigReader.getNationality() ;
    String gender = appConfigReader.getGender();
}
Run Code Online (Sandbox Code Playgroud)


小智 7

你应该@Autowired private Environment env;import org.springframework.core.env.Environment;

然后这样使用它:

env.getProperty("yourPropertyNameInApplication.properties")


Naf*_*ema 6

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

应用程序属性

my.name = kelly

my.dbConnection = {connection_srting:'http://localhost:...', username:'benz', password:'pwd'}
Run Code Online (Sandbox Code Playgroud)

类文件

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

@Value("#{${my.dbConnection}}")
private Map<String,String> dbValues;
Run Code Online (Sandbox Code Playgroud)

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

@Value("${your_name: default value}")
private String msg;
Run Code Online (Sandbox Code Playgroud)


小智 6

@Value Spring注释用于将值注入到Spring管理的bean中的字段中,它可以应用于字段或构造函数/方法参数级别。

\n

例子

\n
    \n
  1. 细绳 value from the annotation to the field
  2. \n
\n
    @Value("string value identifire in property file")\n    private String stringValue;\n
Run Code Online (Sandbox Code Playgroud)\n
    \n
  1. 我们还可以使用@Value注解来注入Map property.

    \n

    首先,我们需要在中定义属性{key: \xe2\x80\x98value\' } form in our properties file:

    \n
  2. \n
\n
   valuesMap={key1: \'1\', key2: \'2\', key3: \'3\'}\n
Run Code Online (Sandbox Code Playgroud)\n

并不是说映射中的值必须用单引号引起来。

\n

现在从属性文件中将此值作为映射注入:

\n
   @Value("#{${valuesMap}}")\n   private Map<String, Integer> valuesMap;\n
Run Code Online (Sandbox Code Playgroud)\n

获取特定键的值

\n
   @Value("#{${valuesMap}.key1}")\n   private Integer valuesMapKey1;\n
Run Code Online (Sandbox Code Playgroud)\n
    \n
  1. 我们还可以使用@Value注解来注入List property.
  2. \n
\n
   @Value("#{\'${listOfValues}\'.split(\',\')}")\n   private List<String> valuesList;\n
Run Code Online (Sandbox Code Playgroud)\n


Jav*_*ner 6

有3种阅读方式application.properties

第一种方式:

使用@Value,EnvironmentInterface@ConfigurationProperties:

@Value("${userBucket.path}")
private String value;
Run Code Online (Sandbox Code Playgroud)

第二种方式:

@Autowired
private Environment environment; // org.springframework.core.env.Environment;

String s = environment.getProperty("userBucket.path");
Run Code Online (Sandbox Code Playgroud)

第三种方式:

@Value("${userBucket.path}")
private String value;
Run Code Online (Sandbox Code Playgroud)

可以用 getter 和 setter 来读取..

参考-这里


Jor*_*var 5

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

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

application.properties
custom-app.enable-mocks = false

@Value("${custom-app.enable-mocks}")
private boolean enableMocks;
Run Code Online (Sandbox Code Playgroud)


小智 5

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

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

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

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