为外部对象中的对象集合添加默认值

rwqw0loc  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(231)

我正在尝试向属性属性添加默认值。我有一个类,其中有另一个类类型作为列表注入。我可以得到所有属性的默认值,甚至依赖于类。我想知道是否有任何方法使用@value添加一个自定义对象的默认值列表。我的模型课是-

package com.example.test.Model;

    import java.util.List;

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

    @Component
    public class Employee {

        @Value("1")
        private Integer id;
        @Value("Anubham")
        private String name;

        @Autowired
        private List<Departments>departments;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public List<Departments> getDepartments() {
            return departments;
        }

        public void setDepartments(List<Departments> departments) {
            this.departments = departments;
        }

        public Employee() {
            super();
        }

        public Employee(Integer id, String name, List<Departments> departments) {
            super();
            this.id = id;
            this.name = name;
            this.departments = departments;
        }

        @Override
        public String toString() {
            return "Employee [id=" + id + ", name=" + name + ", departments=" + departments + "]";
        }
        }
Another one is:
package com.example.test.Model;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Departments {

    @Value("1")
    private int id;

    @Value("computer")
    String subject;

    public Departments() {
        super();
    }

    public Departments(int id, String subject) {
        super();
        this.id = id;
        this.subject = subject;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    @Override
    public String toString() {
        return "Departments [id=" + id + ", subject=" + subject + "]";
    }
}

我以员工身份[id=1,name=anubham,departments=[departments[id=1,subject=computer]]获取输出。我想再有一张部门记录。我想知道是否可以使用@value而不使用任何其他方法。

e0bqpujr

e0bqpujr1#

在您的示例中,“departments”是注入到employee bean中的bean。如果您想要有多个部门,您必须创建接口/抽象“department”,并用您想要的具体值(departmenta,departmentb)在bean中实现它。
但值注解并不意味着注入静态内容,而是从属性文件中注入值。我不知道你想通过这种方式得到什么。

相关问题