2016-04-02 25 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”......而不是转换成数字。

因此,转换方法理解值分隔列表,?