Reputation: 1951
I'm trying to initialize some beans during application start that will be reading from static shared in-memory structures. I was previously using @PostContruct but would like to shift to a more event-based initialization so that I can make use of Spring AOP features (Config, Resources, etc.) and avoid repeating myself.
All data beans implement this interface:
public interface DataInterface {
public void loadData();
public List<String> getResults(String input);
}
I have tried implementing both ServletContextListener
and WebApplicationInitializer
interfaces, but neither seem to get called.
@Service
public class AppInit implements WebApplicationInitializer {
@Autowired
DataInterface[] dataInterfaces;
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// This does not get called
for (DataInterface interface : dataInterfaces)
interface.loadData();
}
}
@WebListener
public class AppContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
// does not get called
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
// does not get called
}
}
I could also try to initialize these classes at the end of the main()
function that returns after I start the SpringApplication.
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
// Can I initialize the DataInterfaces here???
}
}
Seems like there should be a better way.
Edit:
I ended up using the following solution since I wasn't able to receive any of the Context*
events listed in the Spring docs.
@Component
public class DalInitializer implements ApplicationListener {
@Autowired
DataInterface[] dataInterfaces;
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
if (applicationEvent.getClass() == ApplicationReadyEvent.class) {
for (DataInterface interface : dataInterfaces)
interface.loadData();
}
}
}
Upvotes: 0
Views: 44
Reputation: 9516
Use spring application event listeners, see Better application events in Spring Framework
Upvotes: 1