I have some code I want to initialize in my web application. Before I used it as a @PostConstruct in one of my beans, but it didn't feel quite right to me. The place to initialize code in the life cycle, is in my opinion, after the servletcontext has initialized.
That's why I wrote a listener class like this:
public class MyServletContextListener implements ServletContextListener {
@Autowired
UserService userService;
@Autowired
RepairService repairService;
@Override
public void contextInitialized(ServletContextEvent sce) {
// Maak een gewone gebruiker
Address address1 = new Address("Bruul", "5", "2800", "Mechelen");
Person person1 = new Person("Jan", "Peeters", address1);
Client client1 = new Client(person1, "jan.peeters@student.kdg.be", "jan");
// Maak een gewone gebruiker
Address address2 = new Address("Zandstraat", "23", "3000", "Leuven");
Person person2 = new Person("Michel", "Van den Bergh", address2);
Client client2 = new Client(person2, "michel.vandenbergh@gmail.com", "michel");
// Maak een repairer
Address address3 = new Address("Nationalestraat", "5", "2000", "Antwerpen");
Person person3 = new Person("Wouter", "Deketelaere", address3);
Repairer repairGuy1 = new Repairer(person3, "wouter.deketelaere@kdg.be", "jef", "Master");
repairGuy1.rate(4);
// Maak een repairer
Address address4 = new Address("Kleuterstraat", "1", "2500", "Lier");
Person person4 = new Person("Handy", "Man", address4);
Repairer repairGuy2 = new Repairer(person4, "handy.man@handyman.com", "moeilijk", "Bachelor");
repairGuy2.rate(3);
// add users and update een gebruiker met een nieuw wachtwoord
try
{
userService.addUser(client1);
userService.addUser(client2);
userService.addUser(repairGuy1);
userService.addUser(repairGuy2);
userService.updatePassword(repairGuy1, "jef", "wouter");
userService.checkLogin(repairGuy1.getUsername(), "wouter");
}
// ommitted code
Now, this doesn't work, and I presume it's because I can't autowire my services so early in the lifecycle. I can't manually construct a new repair- and userservice because these classes are abstract. Should I move my initialization code somewhere else? Or is there a way to do this so early in the lifecycle?
I fixed this using the InitliazingBean interface