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

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

userBucket.path=${HOME}/bucket

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


当前回答

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

@ value (" $ {userBucket.path} ") private字符串userBucketPath

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

自动装配环境变量到你的类,你需要访问这个属性:

@ autowired 私人环境环境

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

environment.getProperty(“userBucket.path”);

希望这能回答你的问题!

其他回答

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

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

遵循以下步骤。 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.
}

阅读应用程序。属性或应用程序。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()

}

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

使用环境,

@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

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

OR

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

@Configuration
public class AppConfig {

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