简体   繁体   中英

Embedded Tomcat 7 passing Spring application context to servlets

I would like to add web interface to my Java application, so that I can manipulate it's state using HTTP.

I have added to application context a Spring bean for some class that starts embedded Tomcat. This class of course has access to context that creates it. But I would like to store this context somehow in Tomcat class ( org.apache.catalina.startup.Tomcat ) so that later in can be retrieved in Servlets, so that I can do something like this:

    public SomeClass extends extends HttpServlet {    
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                ApplicationContext appContext = getContextStoredEarlierInTomcatClass();
                SomeBeanFromContext sbfc = appContext.getBean("sbfc", ApplicationContext.class);
                sbfc.setSomeProperty(newValue);
            }    
    }

Any idea how I could achieve it?

Thanks!

Classes including Servlets do not require an ApplicationContext to obtain references to String beans. This is done using dependency injection

@Controller
@RequestMapping("/mypage")
public class SomeClass {

   @Autowired
   private SomeBeanFromContext sbfc;

   @RequestMapping(value = "/individualRequest", method = RequestMethod.GET)
   public String doIndividualRequest(HttpServletRequest request) {
      sbfc.setSomeProperty(newValue);
      ...
   }
}

Spring MVC offers a complete method of injecting beans into target web controller classes using @Controller annotated classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM