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

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

userBucket.path=${HOME}/bucket

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


当前回答

你也可以这样做....

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

    @Autowired
    private Environment env;

    public String getConfigValue(String configKey){
        return env.getProperty(configKey);
    }
}

然后无论你想从应用程序中读取什么。属性,只需将键传递给getConfigValue方法。

@Autowired
ConfigProperties configProp;

// Read server.port from app.prop
String portNumber = configProp.getConfigValue("server.port"); 

其他回答

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

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

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

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

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

}

你也可以这样做....

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

    @Autowired
    private Environment env;

    public String getConfigValue(String configKey){
        return env.getProperty(configKey);
    }
}

然后无论你想从应用程序中读取什么。属性,只需将键传递给getConfigValue方法。

@Autowired
ConfigProperties configProp;

// Read server.port from app.prop
String portNumber = configProp.getConfigValue("server.port"); 

可以使用@Value注释从应用程序中读取值。属性/ yml文件。

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

有两种方法,

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

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

OR

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

@Configuration
public class AppConfig {

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