2016-05-24 9 views
-2

我有一個類如下所示。如何使用Guice或Spring根據屬性注入對象列表

public class Person { 

    private String name; 

    public Person(String name) { 
     this.name = name; 
    } 

    public String getName() { 
     return name; 
    } 
} 

我的本意是一個List<Person>注入到哪裏應該從屬性文件中創建的列表中的其他類。 就是這樣。

persons(0)=John 
persons(1)=Jake 
+1

Java配置。註釋。 – justAnotherGuy

+0

非常具體的要求。看起來你必須寫很多自定義代碼。你是否? –

回答

-1

這裏有Spring例子。 嘗試這樣,你可以添加儘可能多的屬性,只要你想。或者只是遍歷properties.In屬性文件,只需設置屬性person=Name。如果屬性文件位於項目資源文件中,則Spring將自動找到它。

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

@Component 
public class MyProperties { 

    @Value("${person}") 
    private String person; 

    public String getPerson(){ 
    return this.person; 
    } 

} 

public class anotherClass { 

@Atowired 
MyProperties myProperties; 

List<Person> createObjectsBasingOnProperties(){ 
    ArrayList<Person> persons = new ArrayList<>(); 
    persons.add(new Person(myProperties.getPerson())); 
    return persons; 

} 

} 
相關問題