Spring引导1.5.2.RELEASE在静态方法中访问application.yml属性

时间:2017-04-24 14:57:00

标签: java spring spring-boot groovy

我有一个Spring boot 1.5.2.RELEASE个应用,我的application.yml

中有以下条目
digsig:
  trustweaver:      
    truststore: truststore.jks
    truststorePassword: xxxxxx

我正在尝试在静态类中访问上面的属性,如下所示,代码编译但在日志记录中获取为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属性吗?

1 个答案:

答案 0 :(得分:2)

首先,您不能将"${...}"用于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
...