Spring 使用对象集合列表中的数据获取空值
我正在尝试在名为CollectionOffemployees的列表中添加几个employee对象。我可以添加数据,但我得到的自定义对象属性的第一条记录为Null。之后将正确插入数据 这是我的控制器Spring 使用对象集合列表中的数据获取空值,spring,spring-boot,Spring,Spring Boot,我正在尝试在名为CollectionOffemployees的列表中添加几个employee对象。我可以添加数据,但我得到的自定义对象属性的第一条记录为Null。之后将正确插入数据 这是我的控制器 @RestController public class CustomController { @Autowired Employees collectionofEmployees; @RequestMapping("/add") public Employees add()
@RestController
public class CustomController {
@Autowired
Employees collectionofEmployees;
@RequestMapping("/add")
public Employees add() {
collectionofEmployees.add(new Employee(1,"XYZ"));
collectionofEmployees.add(new Employee(3, "VTY"));
return collectionofEmployees;
}
这是我的Employees模型类,其中包含员工列表
@Component
public class Employees {
@Autowired
private List<Employee>employees;
public List<Employee> getEmployees() {
return employees;
}
public Employees(List<Employee> employees) {
super();
this.employees = employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public void add(Employee employee)
{
this.employees.add(employee);
}
我得到的输出是{“employees”:[{“id”:null,“name”:null},{“id”:1,“name”:“XYZ”},{“id”:3,“name”:“VTY”}]}
非常感谢您的帮助:)我希望避免空值请尝试从Employee类中删除
@Component
。它由Spring初始化并注入到您的
@Autowired
private List<Employee>employees
@Autowired
私人雇员
尝试从Employee类中删除@组件。它由Spring初始化并注入到您的
@Autowired
private List<Employee>employees
@Autowired
私人雇员
由于我仍然不知道如何避免spring初始化时出现空值,因此出于临时目的,我在add方法下添加了CollectionFemEmployees.getEmployees().remove(0),该方法将从输入中删除空值。因为我仍然不知道如何避免spring初始化时出现空值,出于临时目的,我在add方法下添加了collectionofEmployees.getEmployees().remove(0),该方法将从输入中删除空值。@N它不会在该方法中运行case@YN如果正确,请不要使用@Component
注释模型类。Spring组件由Spring实例化,默认情况下是单例的。这不是您想要的数据模型。您只需在组件中初始化Employees
实例,无需注入它;@RequestMapping(“/hello”)public void add(){collectionofEmployess.add(新员工(1,“XYZ”);collectionofEmployess.add(新员工(3,“VTY”);System.out.println(collectionofEmployess);}@希望你们的意思是像我上面提到的那个样?我认为手动实例化这样的对象不是好习惯。我对spring和学习还是新手。若我错了,请纠正我,您的意思是,如果我们为数据模型添加自定义对象列表,那么通过spring进行注入就没有意义了,因为注入只适用于单个对象?@Ashish34630如果您想自己管理对象,您不需要让spring来管理它们。使用@Component
您要求Spring为您创建对象<代码>@Autowired
使用指定的类型和注释放置的位置设置Spring find对象。在集合中设置@Autowired
,要求Spring使用Spring已知的指定类型的对象创建指定集合。所以,我的坏消息是,我没有说过要从列表中删除@Autowired
。
@Y它不会在该列表中运行case@YN如果正确,请不要使用@Component
注释模型类。Spring组件由Spring实例化,默认情况下是单例的。这不是您想要的数据模型。您只需在组件中初始化Employees
实例,无需注入它;@RequestMapping(“/hello”)public void add(){collectionofEmployess.add(新员工(1,“XYZ”);collectionofEmployess.add(新员工(3,“VTY”);System.out.println(collectionofEmployess);}@希望你们的意思是像我上面提到的那个样?我认为手动实例化这样的对象不是好习惯。我对spring和学习还是新手。若我错了,请纠正我,您的意思是,如果我们为数据模型添加自定义对象列表,那么通过spring进行注入就没有意义了,因为注入只适用于单个对象?@Ashish34630如果您想自己管理对象,您不需要让spring来管理它们。使用@Component
您要求Spring为您创建对象<代码>@Autowired使用指定的类型和注释放置的位置设置Spring find对象。在集合中设置@Autowired
,要求Spring使用Spring已知的指定类型的对象创建指定集合。所以我的坏消息是,我没有说要从列表中删除@Autowired
。