2017-05-08 57 views
0

正如標題,我的自定義屬性:如何獲得文件屬性的內容在春季啓動

#app settings 
my.chassisNum=10 

java代碼:

@PropertySource("classpath:appconf.properties") 
@ConfigurationProperties(prefix = "my") 
@Component 
public class AppConfig { 

    private String chassisNum; 

    public String getChassisNum() { 
     return this.chassisNum; 
    } 

    public void setChassisNum(String chassisNum) { 
     this.chassisNum = chassisNum; 
    } 
} 

當春天開機啓動結束,我得到了「chassisNum 「值是10 當我得到了它在其他地方,當春天開機不啓動完成後,得到‘空’

@Component 
public class CreateBaseFolder { 

    private final Logger logger = LogManager.getLogger(CreateBaseFolder.class); 
    private File f; 
    @Autowired 
    AppConfig appconf; 

    public CreateBaseFolder() { 

     System.out.println(appconf.getChassisNum()); 


    } 

我嘗試了很多方法來獲得它的價值,但是是false.such如:implements InitializingBean,@DependsOn ...

+0

你是什麼春天啓動的意思沒有完全 – pvpkiran

+0

怎麼就縱身能夠自動線中不存在的物體開始......你試圖訪問一個構造函數中自動有線領域......春天只能注入依賴關係存在於構造函數之後的對象中。 –

+0

是否沒有辦法在項目啓動過程中獲取配置文件的屬性值?也就是說,在加載完其他Bean之後無法加載AppConfig? –

回答

0

假設你有application.properties與內容:

foo.bar=Jerry 

您將使用註釋@Value

package com.example; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.stereotype.Component; 

@Component 
public class GetPropertiesBean { 

    private final String foo; 

    @Autowired 
    public GetPropertiesBean(@Value("${foo.bar}") String foo) { 
     this.foo = foo; 
     System.out.println(foo); 
    } 

} 

當然,我們需要一個切入點:

package com.example; 

import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 

@SpringBootApplication 
public class Application { 

    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 

} 

然後運行類應用作爲Spring Boot應用程序,組件是autoload,y OU會看到結果在控制檯屏幕:

傑裏

enter image description here

0

@Resource private環境;

environment.getProperty(「my.chassisNum」);

通過這個,你將能夠訪問my.chassisNum屬性。

0

您可以通過@Value註釋實現它,這個註釋可以在他的評論中提到的方法參數作爲@Do Nhu Vy使用。你也可以使用它的構造函數參數以及一個類的級別。 e.g:每

@Service 
    Class TestService { 

    @Value("${my.chassisNum}") 
    private String chassisNum; 

    public void printChassisNum { 
    System.out.println(chassisNum) 
    } 
    } 

由於這是doc

在註解表示爲受影響的參數的缺省值表達式的字段或方法/構造參數的水平。

通常用於表達式驅動的依賴注入。還支持動態解析處理程序方法參數,例如在 Spring MVC中。

一個常見的用例是使用「#{systemProperties.myProp}」樣式表達式來指定默認字段值。

請注意,@Value註釋的實際處理由BeanPostProcessor執行,這意味着您不能在BeanPostProcessor或BeanFactoryPostProcessor類型中使用@Value 。請 諮詢javadoc的AutowiredAnnotationBeanPostProcessor類 (默認情況下,檢查是否存在此註釋)。