2017-04-24 80 views
0

訪問application.yml性質我有一個Spring boot 1.5.2.RELEASE應用下面的條目在我application.yml春天開機1.5.2.RELEASE靜態方法

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屬性?

+1

你的變量不能 – pvpkiran

+0

你不能用'「$是靜態{...} 「'groovy,因爲那些被groovy用來替換字符串。使用單引號代替:''{{...}'' – cfrick

+0

如果它的非靜態我不能在靜態方法中訪問它,並且我想'CustomHttpsSSLConfig'被初始化爲靜態,以便'SSLContext'被初始化用'truststore'和'keystore'來調用'Https' web服務。它現在工作正常,但我已經在'CustomHttpsSSLConfig'中對'keystore'和'truststore'進行了硬編碼,但是我希望它們在'application.yml'中配置。 – RanPaul

回答

2

首先,你不能使用"${...}"作爲spring變量,因爲Groovy本身使用它來替換字符串。請使用單引號('${...}'),以便Groovy保持原樣。

接下來不要爲此使用靜態變量,並讓它在您要求設置變量之前進行工作。下面是一個完整,工作示例:

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 
... 
+0

謝謝,這個解決方案的作品 – RanPaul