Search code examples
javaspringlistenerapplicationcontextspring-web

Add listener spring web after Applicationcontext is loaded


I'm not sure if it's working, we have a project that loads a file .txt, that is users created on previous deployments. The problem was that the Applicationcontext wasn't loaded, and throws NullPointerException, since the method that loads the file is @Autowired and this is what I did trying to solve it:

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class TestListener implements ApplicationListener{

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
    }
}

this is the web.xml for the project and the listener:

<listener>
    <listener-class>TestListener</listener-class>
</listener>

The point is to create a listener, is this correct?


Solution

  • Two options come to mind:

    InitializingBean:

    @Component
    public class FileLoader implements InitializingBean {
        public void afterPropertiesSet() throws Exception {
            // load file
        }
    }
    

    This should get called after the context has loaded.

    @PostConstruct:

    @Component
    public UserService {
        private List<Customer> registeredCustomers;
        // ...
    
        @PostConstruct
        public void loadPreviouslyRegisteredUsers() {
            registeredCustomers = loadFile();
        }
    }
    

    I like this better; the @PostConstruct method will be called after the service bean has been created, which is the best opportunity to load the file.

    Sorry if this doesn't really answer your question about the ApplicationContextListener, but it sounds like that's what you're trying to do.