我有一个 Spring boot 1.5.2.RELEASE
应用程序,application.yml
中包含以下条目
digsig:
trustweaver:
truststore: truststore.jks
truststorePassword: xxxxxx
我试图在静态类中访问上述属性,如下所示,代码编译但在日志记录中得到 null 为 caTrustStore = null
public class CustomHttpsSSLConfig {
@Value("${digsig.trustweaver.truststore}")
private static String caTrustStore;
public static void init() {
LOGGER.info("caTrustStore = "+caTrustStore);
//method implementation
}
}
我还尝试在主 groovy 类中访问它,如下所示
@SpringBootApplication
public class DigSigServiceApplication {
@Value("${digsig.trustweaver.truststore}") static String caTrustStore;
private static final Logger LOGGER = LoggerFactory.getLogger(this.class);
public static void main(String[] args) {
LOGGER.info("caTrustStore caTrustStore = "+caTrustStore );
SpringApplication.run(DigSigServiceApplication.class, args);
}
}
但出现编译错误以下
Error:(15, 12) Groovyc: Apparent variable 'digsig' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'digsig' but left out brackets in a place not allowed by the grammar.
有人可以帮助我访问 application.yml
属性吗?
最佳答案
首先,您不能使用 "${...}"
作为 spring 变量,因为 Groovy 本身使用它来替换字符串。请改用单引号 ('${...}'
),以便 Groovy 保持它们原样。
接下来不要使用静态变量,让 spring 在你要求设置变量之前完成它的工作。这是一个完整的工作示例:
package x
@SpringBootApplication
@groovy.util.logging.Slf4j
class DigSigServiceApplication {
@Value('${digsig.trustweaver.truststore}')
String caTrustStore;
static void main(String[] args) {
org.springframework.boot.SpringApplication.run(DigSigServiceApplication, args)
}
@Bean
CommandLineRunner init() {
log.info("caTrustStore = $caTrustStore")
}
}
运行
digsig_trustweaver_truststore=XXX spring run spring.groovy
输出:
...
2017-04-24 17:21:59.125 INFO 14811 --- [ runner-0] x.DigSigServiceApplication : caTrustStore = XXX
...
关于java - Spring boot 1.5.2.RELEASE 在静态方法中访问 application.yml 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43591467/