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

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

userBucket.path=${HOME}/bucket

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


当前回答

对我来说,以上这些方法对我都没有直接作用。 我所做的是:

另外,我补充了@Rodrigo Villalba Zayas的回答 实现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);
    }
}

其他回答

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

阅读应用程序。属性或应用程序。Yml属性遵循以下步骤:

在应用程序中添加属性。属性或application.yaml 创建配置类并添加属性

application.jwt.secretKey=value
application.jwt.tokenPrefix=value
application.jwt.tokenExpiresAfterDays=value ## 14
application:
  jwt:
    secret-key: value
    token-prefix: value
    token-expires-after-days: value ## 14
@Configuration("jwtProperties") // you can leave it empty
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "application.jwt") // prefix is required
public class JwtConfig {
    private String secretKey;
    private String tokenPrefix;
    private int tokenExpiresAfterDays;

    // getters and setters
}

注意:在.yaml文件中,你必须使用kabab-case

现在使用配置类实例化它,你可以手动或依赖注入。

public class Target {

  private final JwtConfig jwtConfig;

  @Autowired
  public Target(JwtConfig jwtConfig) {
      this.jwtConfig = jwtConfig;
  }

  // jwtConfig.getSecretKey()

}

您可以使用@Value从应用程序加载变量。如果你在一个地方使用这个值,那么@ConfigurationProperties是一个更好的方法,但是如果你需要一个更集中的方式来加载这些变量。

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

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

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

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

然后这样使用它: env.getProperty(“yourPropertyNameInApplication.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;

如果你在申请中没有房产。属性,则可以使用默认值

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