In the program, some data we want to be ready when the program is started, and only once, in the application scope, we usually use listener to prepare the data. However, using listener to prepare the data for the application scope, there are some considerations when getting the container.
public class Initlistener implements Servletcontextlistener {public void Contextinitialized (Servletcontextevent SCE) {//Get container with related service object ApplicationContext AC = Webapplicationcontextutils.getwebapplicationcontext (Sce.getservletcontext ()); Privilegeservice Privilegeservice = (privilegeservice) ac.getbean ("Privilegeserviceimpl");// Prepare data:topprivilegelistlist<privilege> topprivilegelist = Privilegeservice.findtoplist (); Sce.getservletcontext (). SetAttribute ("Topprivilegelist", topprivilegelist); System.out.println ("------------> Prepared Data <------------");//Prepare Data:allprivilegeurlscollection<string> Allprivilegeurls = Privilegeservice.getallprivilegeurls (); Sce.getservletcontext (). SetAttribute ("Allprivilegeurls ", Allprivilegeurls); System.out.println ("------------> Prepared Data allprivilegeurls <------------");} public void contextdestroyed (Servletcontextevent arg0) {}
- the listener is configured in Web. XML, by default, by reflection generation instance, to this object instance to execute
- Does not get from the spring container, Tomcat does not find the spring container, so annotations cannot be used here
- If you use annotations, you generate two objects, a tomcat-generated object, a spring container-injected object
- Tomcat uses the objects that it produces, and the objects that spring manages are not used by anyone
Preparing application scope data using listener