Reputation: 340
I am trying to add few employee objects inside the list named collectionofEmployees here.I am able to add the data but i am getting first record for custom object attributes as nulls.The data is getting inserted after that properly.
Here is my controller.
@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;
}
Here is my Employees Model class which contains list of employee
@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);
}
Here is my employee class
@Component
public class Employee {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public Employee() {
super();
}
public Employee(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
The output i am getting is as {"employees":[{"id":null,"name":null},{"id":1,"name":"XYZ"},{"id":3,"name":"VTY"}]}
Help would be appreciated alot:)I want to avoid nulls
Upvotes: 0
Views: 466
Reputation: 340
As i still dont know how to avoid nulls at time of intialisation done by spring,for temporary purpose i have added collectionofEmployees.getEmployees().remove(0) under add method which removes the nulls from the input.
Upvotes: 0
Reputation: 66
Try to remove @Component
from Employee class. It is initialized by Spring and injected to your
@Autowired
private List<Employee>employees
Upvotes: 2