java - Spring boot 1.5.2.RELEASE 在静态方法中访问 application.yml 属性

标签 java spring spring-boot groovy

我有一个 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/

相关文章:

java - 使用多个表单在 View 上提交表单时出现 Spring "Neither BindingResult nor plain target object for bean name"错误

java - Android Rest 客户端 - JSON 响应中的连字符名称

java - 我需要防止使用反射从父类(super class)获取私有(private) Properties 字段。如何使用 Java 安全管理器来执行此操作

java - 与 JDO 和 GAE 的多对一关系

java - 创建一个新对象并调用方法 spring 配置

java - 如何部署 "Building REST Services with Spring"教程?

maven - 无法使用@Value在Spring应用程序中获取maven project.version属性

java - swagger-codegen-maven-plugin 在生成 API 类时忽略我为 ZonedDateTime 设置的导入映射

java - TreeMap 内存使用

java - 使用 RxJava Observables 组合成并行下载图像的 Map