Reputation: 223
I am working on Spring 4 mvc and hibernate I want to run code on the server startup that will use the get data from the database then do some business logic
where can I put my code I tried to put the code
org.springframework.web.servlet.support.AbstractDispatcherServletInitializer.onStartup(ServletContext)
but I was not able to use @Autowired variables
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Autowired
TaskDAO task;
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { SpringRootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { SpringWebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
task.getAllTasks()
// TODO Auto-generated method stub
super.onStartup(servletContext);
}
}
Upvotes: 1
Views: 2260
Reputation: 2144
You are not able to autowire variables because your class is not managed by spring. So annotate your class with @Component
annotation.
Then you can define a method that will do your logic (for example onStartup method) and annotate it with the @PostConstruct
annotation as explained in this answers.
How to call a method after bean initialization is complete?
It will execute the method after the beans initialization.
This could be your class:
@Component
public class WebInitializer{
@Autowire
TaskDAO task;
@PostConstruct
private void onStartup(){
task.getAllTasks();
// Do whatever you want
}
}
Upvotes: 2