I'm trying to use PicoContainer in a servlet based app running on Tomcat. Configuration apparently works in debug but unless as I supposed Servlet classes are not injected by construnctor and neighter by setter. Aren't servlet classes supposed to be injected? If not, how can I use the container in a servlet based app?
1 Answers
There's no IoC container that actually injects the servlets. They're instantiated by tomcat in your case. Typical Pico components are controllers, DAOs, business logic stuff etc.
You can actually implement your web-app in two ways:
1) put pico filter in play: your Controllers should be request scope components implementing Lifecycle interface. So such component will have request injected and then start() called by the container. Actually in this approach you will not have servlets at all. Probably makes sense to have single Router controller in request scope which will delegate specific url processing to other container components.
2) as you said, ScopedContainers hides containers for external code, so you have to write your own PicoServletContainerListener (just take existing source and make scoped containers available to your code) in this method you can write usual servlets and delegate then to pico components

- 1,250
- 10
- 15
-
containers.getApplicationContainer() appear as private method to me – Felice Pollano Sep 04 '14 at 09:21
-
I accept your response but I don't agree with the strategy. Servlet class itself has to be injected because as far the Composition root is from your app plumbing as better it is. If I can't inject the constructor of the servlet, I have to insert container logic into the servlet and this is an antipattern, so is better not to use a container at all. I can obtain this in .NET with NancyFX, just to say. Anyway I'm moving to use restlet instead of plain servlets. Maybe I will be more luky. – Felice Pollano Sep 04 '14 at 18:13
-
You may be right about not using container :) Actually you have not explained why do need it. But injecting a servlet is useless. Injecting INTO a servlet may have sense instead. Servlet object is stateless, you can't do anything useful with it from other app components. You're right that composition root from the app looks nicer, but this requires deep integration of IoC container inside the web container. It's hard to do with Tomcat, but quite possible with Jetty or internal http server in sun JDK. – xeye Sep 04 '14 at 20:20
-
wouldn't be difficult if they just provide a configuratable factory for the servlet – Felice Pollano Sep 04 '14 at 20:29
-
I need a container, because I know from experience than when the app grown it is useful to have. And having in .NET is a breeze – Felice Pollano Sep 04 '14 at 20:30
-
there's a factory. somewhere deep in sources of Tomcat :) it just not as embedded and pluggable as Jetty. – xeye Sep 05 '14 at 06:13