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

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

userBucket.path=${HOME}/bucket

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


当前回答

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

其他回答

有两种方法,

你可以直接在类中使用@Value

    @Value("#{'${application yml field name}'}")
    public String ymlField;

OR

要使它干净,你可以清除@Configuration类,在那里你可以添加所有的@value

@Configuration
public class AppConfig {

    @Value("#{'${application yml field name}'}")
    public String ymlField;
}

属性中的@Value("${property-name}") 应用程序。属性 @配置或@组件。

我尝试的另一种方法是用下面的方式创建一个Utility类来读取属性

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

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

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

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

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

也许它可以帮助其他人: 你应该注入@Autowired私有环境env;from import org.springframework.core. environment;

然后这样使用它: env.getProperty(“yourPropertyNameInApplication.properties”)