我想访问应用程序中提供的值。属性,例如:
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
logging.file=${HOME}/application.log
userBucket.path=${HOME}/bucket
我想访问userBucket。在Spring Boot应用程序的主程序中的路径。
我想访问应用程序中提供的值。属性,例如:
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
logging.file=${HOME}/application.log
userBucket.path=${HOME}/bucket
我想访问userBucket。在Spring Boot应用程序的主程序中的路径。
当前回答
应用程序可以从应用程序中读取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;
其他回答
@ value (" $ {userBucket.path} ") private String userBucketPath;
另一种方法是将org.springframework.core. environment注入到bean中。
@Autowired
private Environment env;
....
public void method() {
.....
String path = env.getProperty("userBucket.path");
.....
}
阅读应用程序。属性或应用程序。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
你也可以这样做....
@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");