我想访问应用程序中提供的值。属性,例如:

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

userBucket.path=${HOME}/bucket

我想访问userBucket。在Spring Boot应用程序的主程序中的路径。


当前回答

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

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从环境变量中的属性源文件(在您的类中)设置值。 所以你可以很容易地获取后记。 可通过系统环境变量访问。

3.@ConfigurationProperties注释。

这主要用于Spring项目中加载配置属性。 它根据属性数据初始化实体。 @ConfigurationProperties标识要加载的属性文件。 @Configuration基于配置文件变量创建bean。 @ConfigurationProperties(prefix = "user") @ configuration(“用户数据”) 类用户{ //属性及其getter / setter } @ autowired private UserData; userData.getPropertyName ();

其他回答

@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();

}

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

...
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"));
    }
} 

实际上有三种方法来读取应用程序。属性文件,

使用环境,

@Autowired
Environment environment

environment.getProperty({propertyName})

或者使用@Value,

@Value("${property}")

但是@Value的问题是,如果值不在属性文件中,它可能会抛出异常

建议使用@ConfigurationProperties

@ConfigurationProperties("userBucket")
public class test{
  private String path;
  //getters and setters
}

详细示例-读取application.properties

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

您可以访问该应用程序。属性文件值使用:

@Value("${key_of_declared_value}")