Recently, due to the servlet calling Spring bean in the project, all the beans in the project are completed in Annotation mode, such as @ service, @ repository, and @ resource, however, spring container management does not recognize servlets and filters, so it cannot be referenced using annotations. After checking the information on the Internet, you can see the following code:
Method 1: instantiate the bean in the init method of servlet. After initialization, you can call the method in bean in servlet.
- Webapplicationcontext cont = webapplicationcontextutils. getrequiredwebapplicationcontext (config. getservletcontext ());
- TS = (testservice) cont. getbean ("testservice") // ts is the declared class variable. By default, the name in the brackets is the class name of the bean, and the first letter is lowercase. You can also set a unique name, for example, @ Service (value = "testservice ")
Copy code
Method 2: Get it directly in the servlet dopost method. The Code is as follows:
- Webapplicationcontext cont = webapplicationcontextutils. getrequiredwebapplicationcontext (request. getsession (). getservletcontext ());
Copy code
However, in my project, no bean can be obtained using any of the above methods, because the above two methods are only valid for the bean configured in XML, and the annotation bean cannot be obtained, finally, I saw an article on "Spring Processing source code analysis for annotation (annotation)-scanning and reading bean definitions" on the Internet, and finally solved this problem. The Code is as follows:
Code 1: Service Interface
- Package com. Test. Web. Service;
- Public interface itestservice {
- Public void test (); // Test Method
- }
Copy code
Code 2: implement interfaces and use annotations
- Package com. Test. Web. Service. impl;
- Import org. springframework. stereotype. Service;
- Import com. taokew.web. Test. itestservice;
- // The annotation section here provides a unique name, such as @ Service (value = "testserviceimpl"), which is equivalent to the bean ID in xml configuration.
- @ Service
- Public class testserviceimpl implements itestservice {
- @ Override
- Public void test (){
- System. Out. println ("test printing ");
- }
- }
Copy code
Code 3: Obtain the annotation bean in the servlet and call its test method
- Annotationconfigapplicationcontext CTX = new annotationconfigapplicationcontext ();
- CTX. Scan ("com. Test. Web. Service .*");
- CTX. Refresh ();
- Testserviceimpl service = CTX. getbean (testserviceimpl. Class); // you can also use CTX. getbean ("testserviceimpl") here ")
- Service. Test ();
Copy code
In this way, you can call Spring annotation bean in servlet or filter, in fact, the whole process is to simulate springmvc to scan the component package during initialization, complete the registration of all beans, and store them in the Management container. If you have a better solution, I hope you can give me some advice!