我想访问应用程序中提供的值。属性,例如:
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应用程序的主程序中的路径。
当前回答
阅读应用程序。属性或应用程序。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注释并访问您所使用的Spring bean中的属性
@Value("${userBucket.path}")
private String userBucketPath;
Spring Boot文档的Externalized Configuration部分解释了您可能需要的所有细节。
获取财产价值的最佳方法是使用。
1. 使用Value注释
@Value("${property.key}")
private String propertyKeyVariable;
2. 使用环境bean
@Autowired
private Environment env;
public String getValue() {
return env.getProperty("property.key");
}
public void display(){
System.out.println("# Value : "+getValue);
}
有两种方法,
你可以直接在类中使用@Value
@Value("#{'${application yml field name}'}")
public String ymlField;
OR
要使它干净,你可以清除@Configuration类,在那里你可以添加所有的@value
@Configuration
public class AppConfig {
@Value("#{'${application yml field name}'}")
public String ymlField;
}
我也有这个问题。但是有一个很简单的解决办法。只需要在构造函数中声明你的变量。
我的例子:
application.propperties:
#Session
session.timeout=15
SessionServiceImpl经济舱:
private final int SESSION_TIMEOUT;
private final SessionRepository sessionRepository;
@Autowired
public SessionServiceImpl(@Value("${session.timeout}") int sessionTimeout,
SessionRepository sessionRepository) {
this.SESSION_TIMEOUT = sessionTimeout;
this.sessionRepository = sessionRepository;
}
应用程序。Yml或application.properties
config.value1: 10
config.value2: 20
config.str: This is a simle str
MyConfig类
@Configuration
@ConfigurationProperties(prefix = "config")
public class MyConfig {
int value1;
int value2;
String str;
public int getValue1() {
return value1;
}
// Add the rest of getters here...
// Values are already mapped in this class. You can access them via getters.
}
任何想要访问配置值的类
@Import(MyConfig.class)
class MyClass {
private MyConfig myConfig;
@Autowired
public MyClass(MyConfig myConfig) {
this.myConfig = myConfig;
System.out.println( myConfig.getValue1() );
}
}