2016-04-02 24 views
2

的列表,我有一個關於屬性在春季與性質的工作,使我與春性工作對象

Valores.properties疑問

estudiante.nombre=Antonio, Juan , Maria, Raquel 
estudiante.edad=28,20,21,23 

現在我有一個類制定豆

public class Estudiante { 

    public Estudiante() { 
    } 

    public Estudiante(String nombre, Integer edad) { 
     super(); 
     this.nombre = nombre; 
     this.edad = edad; 
    } 

    @Value("${estudiante.nombre}") 
    private String nombre; 

    @Value("${estudiante.edad}") 
    private Integer edad; 

    public Integer getEdad() {  
     return edad; 
    } 

    public void setEdad(Integer edad) {  
     this.edad = edad; 
    } 

    public String getNombre() {  
     return nombre; 
    } 

    public void setNombre(String nombre) { 
     this.nombre = nombre; 
    } 

    @Override 
    public String toString() { 
     return '\n' +"Estudiante{" + "nombre=" + nombre + ", edad=" + edad + '}'; 
    } 

} 

一個Java類,以使配置

@Configuration 
@PropertySource(value="classpath:valores.properties") 
public class AppConfig { 

    @Value("#{'${estudiante.nombre}'.split(',')}") 
    private List<String> nombres; 
    @Value("#{'${estudiante.edad}'.split(',')}")  
    private List<Integer> edades; 

    @Bean 
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 
     return new PropertySourcesPlaceholderConfigurer(); 
    } 

    public List<String> getNombres() { 
     return nombres; 
    } 


    public List<Integer> getEdades() { 
     return edades; 
    } 

    public List<Estudiante> getListaStudents() { 

     List<Estudiante> listaStudents = new ArrayList<>(); 

     for (int i= 0;i< nombres.size();i++){ 
      listaStudents.add(new Estudiante(nombres.get(i),edades.get(i))); 
     } 

     return listaStudents; 
    } 

} 

和主Java類

public class Principal { 

    public static void main(String[] args) { 

     ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); 
     AppConfig appConfig = context.getBean(AppConfig.class); 
     System.out.println(appConfig.getListaStudents()); 
     ((ConfigurableApplicationContext)context).close(); 
    } 

} 

該項目工程和輸出是OK

[ 
Estudiante{nombre=Antonio, edad=28}, 
Estudiante{nombre= Juan , edad=20}, 
Estudiante{nombre= Maria, edad=21}, 
Estudiante{nombre= Raquel, edad=23}] 

但我不知道這是否是發展的正道。我不想在AppConfig類中構建一個getListaStudents()方法來創建objets列表,我不喜歡在Spring中使用new()方法

我認爲這不是一個好主意,但我不知道其他解決方法。 任何解決方案或任何想法?

在此先感謝

回答

2

我覺得這是有一些改進適當的解決辦法,但根據數據大小和要求,您可能不希望加載從屬性文件的數據。屬性文件通常用於配置選項,例如針對不同的環境數據庫配置,緩存配置等。

在你AppConfig的,你不需要使用SpringEL解析這樣的ListInteger S或String S,

@Value("#{'${estudiante.nombre}'.split(',')}") 
private List<String> nombres; 

我會建議使用這樣的事情,而不是,

@Value("${estudiante.edad}") List<Integer> nombres 

但對於這個工作,你需要有一個addtional bean配置對於Spring的ConversionService

@Bean 
public ConversionService conversionService() { 
    return new DefaultConversionService(); 
} 

這樣Spring的轉換服務將默認轉換器轉換成字符串或整數列表,這樣就可以避免稍差可讀#{'${estudiante.edad}'.split(',')}@Value註解。

現在,您可以使用以上@Value直接在新的bean中使用,以創建一組這樣的學生。

@Bean 
public List<Estudiante> getStudents(
     @Value("${estudiante.edad}") List<Integer> numbers, 
     @Value("${estudiante.nombre}") List<String> names) { 

    List<Estudiante> listaStudents = new ArrayList<Estudiante>(); 
    for (int i= 0;i< numbers.size();i++){ 
     listaStudents.add(new Estudiante(names.get(i), numbers.get(i))); 
    } 

    return listaStudents; 
} 

,您可以用@Resource注入的Estudiante的名單,

@Resource(name = "getStudents") 
private List<Estudiante> estudiantes; 

我看不出什麼錯與new關鍵字生成Estudiante對象。正如我們在@Bean註釋的其他方法中使用new這是一個完全有效的方案。如果你想,以避免new創造Estudiante不管什麼原因,你可以注入ApplicationContext並獲得EstudianteEstudiante studiante = applicationContext.getBean(Estudiante.class);和別忘記,以紀念Estudiante@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

我不喜歡建立一個方法getListaStudents( )在AppConfig的類來使物體

列表據我所知,是因爲他們需要有自己的創造EstudianteList一個對象沒有簡單且適當方式值。您可以將學生創建爲其自己的配置類,例如EstudianteConfiguration,並將其導入您的主AppConfig類,並帶有@Import註釋。

0

Uooohh ..這是一個很好的解決方案。 感謝您的時間Bunti(並感謝其他用戶的修訂版)

我已經開發了一個解決方案與您的建議,買我有一個問題,趕上並拆分屬性文件的值。

新類(與建議)是這裏

@Configuration 
@PropertySource(value="classpath:valores.properties") 
public class AppConfig { 

    @Resource(name = "getStudents") 
    private List<Estudiante> estudiantes; 

    public List<Estudiante> getEstudiantes() { 
     return estudiantes; 
    } 

    @Bean 
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 
     return new PropertySourcesPlaceholderConfigurer(); 
    } 

    @Bean 
    public ConversionService conversionService() { 
     return new DefaultConversionService(); 
    } 

    @Bean 
    public List<Estudiante> getStudents(
     @Value("${estudiante.nombre}")List<String> nombres, 
     @Value("${estudiante.edad}") List<Integer> numbers 
     ) { 

     List<Estudiante> listaStudents = new ArrayList<>(); 
     for (int i= 0;i< nombres.size();i++){ 
      listaStudents.add(new Estudiante(nombres.get(i),numbers.get(i))); 
      //listaStudents.add(new Estudiante(nombres.get(i))); 
     } 
     return listaStudents; 
    } 
} 

跑步,我有幾個例外,但我認爲這是同一個問題

由於只有抓住屬性文件的字符串值(在這個例子中,從名字)系統中的值寫入

[Estudiante{nombre=Antonio, Juan , Maria, Raquel, edad=null}] 

要允許這個輸出,我曾評論爲整數值(所以,年齡/ EDAD是NUL所有引用1 ...沒問題)

真的,這不`噸分裂屬性文件和字符串值是 「A,B,C,d ......」(和大小爲1)

所以,當我使用屬性文件

estudiante.nombre=Antonio, Juan , Maria, Raquel 
estudiante.edad=28,20,21,23 

,趕上字符串和Integer有一個例外

Exception encountered during context initialization - cancelling refresh attempt 
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appConfig': 
Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'getStudents' defined in test.AppConfig: 
Unsatisfied dependency expressed through constructor argument with index 1 of type [java.util.List]: : 
Failed to convert value of type 'java.lang.String' to required type 'java.util.List'; nested exception is java.lang.NumberFormatException: 
For input string: "28,20,21,23"; nested exception is org.springframework.beans.TypeMismatchException: 
Failed to convert value of type 'java.lang.String' to required type 'java.util.List'; 
nested exception is java.lang.NumberFormatException: For input string: "28,20,21,23" 

唯一的例外是合乎邏輯的。我期望一個數字解析......但我抓住「28,20,21,23」......而不是轉換成數字。

因此,轉換方法理解值分隔列表,?