2014-11-03 217 views
0

在我當前的spring項目中,我正在尋找一種方法來爲我的一些POJO類的屬性賦值。根據變量賦值給變量

此功能類似於使用註釋PathVariableModelAttribute用於在控制器的方法的一些參數的:當一個參數被註釋與該註解的一個,所述自己的系統讀出的值。此參數和分配給該變量,無需使用<variable> = <value>

在我的項目,我有一些POJO類是這樣的:

class Class { 

    private <type> <attribute> 

    public <type> get<attribute>() { 
     return <attribute>; 
    } 

    public void set<attribute>(<type> <parameter>) { 
     <attribute> = <parameter>; 
    } 

} 

如果添加批註的屬性(例如:@Setting),當我創建這個類的一個新實例,該系統應讀取文件中的值並分配給變量。

任何人都可以告訴我該怎麼做?

+1

這將有助於http://stackoverflow.com/questions/20782673/creating-custom-annotation-in-spring -mvc-and-getting-httpservletrequest-object – 2014-11-03 13:23:37

回答

1

您可以使用Spring @PropertySource & @Value註釋。我的意思是這樣的:

@Value("${sourceLocation:c:/temp/input}") 
    private String source; 

    @Value("${destinationLocation:c:/temp/output}") 
    private String destination; 

    @Autowired 
    private Environment environment; 

    public void readValues() { 
     System.out.println("Getting property via Spring Environment :" 
       + environment.getProperty("jdbc.driverClassName")); 

     System.out.println("Source Location : " + source); 
     System.out.println("Destination Location : " + destination); 

有一個很好的跟上時代的blogpost here

+0

是否可以使用'@ Value'參數作爲我應用程序的其他類的現有方法的返回值而不是'$ {...}'? – 2014-11-03 14:50:00

+0

根據值的javadoc http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Value.html一個常見的用例是使用默認字段值「#{systemProperties.myProp}」樣式表達式。所以我認爲你需要一個註解'@PostConstruct'的初始化方法,並將其他類對象作爲自動裝配。您可以檢查@PostConstructor註釋。 – erhun 2014-11-03 15:50:06