在 Spring 中使用属性来制作对象列表

Ant*_*nio 5 java spring properties

我正在处理 Spring 中的属性,但我对这些属性有疑问

Valores.properties

estudiante.nombre=Antonio, Juan , Maria, Raquel
estudiante.edad=28,20,21,23
Run Code Online (Sandbox Code Playgroud)

现在我有一个班级来开发 bean

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 + '}';
    }

}
Run Code Online (Sandbox Code Playgroud)

用于进行配置的 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

和主要的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();
    }

}
Run Code Online (Sandbox Code Playgroud)

程序运行正常,输出正常

[
Estudiante{nombre=Antonio, edad=28}, 
Estudiante{nombre= Juan , edad=20}, 
Estudiante{nombre= Maria, edad=21}, 
Estudiante{nombre= Raquel, edad=23}]
Run Code Online (Sandbox Code Playgroud)

但我不知道这是否是正确的发展方式。我不喜欢在 AppConfig 类中构建方法 getListaStudents() 来制作对象列表,我不喜欢在 Spring 中使用 new() 方法

我认为这不是一个好主意,但我不知道其他解决方法。任何解决方案或任何想法?

提前致谢

Bun*_*nti 2

我认为这是一种正确的方法,几乎​​没有什么改进,但根据数据大小和要求,您可能希望从属性文件加载数据。属性文件通常用于配置选项,例如不同环境的数据库配置、缓存配置等。

\n\n

在你的AppConfig中,你不需要像这样使用SpringEL来解析a Listof Integers或s,String

\n\n
@Value("#{\'${estudiante.nombre}\'.split(\',\')}")\nprivate List<String> nombres;\n
Run Code Online (Sandbox Code Playgroud)\n\n

我建议改用这样的东西,

\n\n
@Value("${estudiante.edad}") List<Integer> nombres\n
Run Code Online (Sandbox Code Playgroud)\n\n

但要实现这一点,您需要为 Spring 的ConversionService提供一个额外的 bean 配置

\n\n
@Bean\npublic ConversionService conversionService() {\n    return new DefaultConversionService();\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这样,Spring 的转换服务将具有默认转换器来转换字符串或整数列表,这样您就可以避免注释#{\'${estudiante.edad}\'.split(\',\')}中可读性较差的情况@Value

\n\n

现在您可以使用上面的内容@Value直接在新 bean 中使用来创建一组这样的学生。

\n\n
@Bean\npublic List<Estudiante> getStudents(\n        @Value("${estudiante.edad}") List<Integer> numbers,\n        @Value("${estudiante.nombre}") List<String> names) {\n\n    List<Estudiante> listaStudents = new ArrayList<Estudiante>();\n    for (int i= 0;i< numbers.size();i++){\n        listaStudents.add(new Estudiante(names.get(i), numbers.get(i)));\n    }\n\n    return listaStudents;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

你可以Estudiante用 s注入列表@Resource

\n\n
@Resource(name = "getStudents")\nprivate List<Estudiante> estudiantes;\n
Run Code Online (Sandbox Code Playgroud)\n\n

我不认为Estudiante使用关键字创建对象有什么问题new。正如我们new在其他带有注释的方法中使用的那样,@Bean这是一个完全有效的场景。如果您愿意,出于某种原因避免new创建Estudiante,您可以注入ApplicationContext并获取EstudianteEstudiante studiante = applicationContext.getBean(Estudiante.class);并且不要忘记用以下标记来标记Estudiante@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

\n\n
\n

我 d\xc3\xb3n\ 不喜欢在 AppConfig 类中构建方法 getListaStudents() 来创建对象列表

\n
\n\n

据我所知,没有简单且正确的方法来创建List对象Estudiante,因为它们需要有自己的值。您可以将学生创建为其自己的配置类,例如并使用@ImportEstudianteConfiguration注释将其导入到您的主AppConfig类中。

\n