Spring: link between WebApplicationContext and ApplicationContext? - spring

I am working on a Spring application. I started from creating a small java app using spring. Later, it became necessary to add a web interface. I decided to use Spring MVC. Now I am confused. In my web.xml I have
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/mvc-dispatcher-servlet.xml,
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
where mvc-dispacher-servlet.xml contains beans necessary for web logic while applicationContext.xml contains beans performing some specific operations. My question is: Are beans in these files going to be aware of each other? Is it going to be a one big container which includes beans from both config files? or these containers are separate?

Yes it will be in one context which will be loaded from the web application context. Its the same as you would do when using the application context and passing in multiple files to it.

Related

Eclipse Spring MVC Project Configuration Files

I have created a Spring MVC project through eclipse. I believe I used some plugins to generate the project directory. I find here there configuration files.
web.xml
root-context.xml
servlet-context.xml
I am kinda of familiar with Spring MVC & its dependency injection. However I have problems understanding the last two configuration files (root-context & servlet-context).
What kind of configurations do they contain?
Also in may online examples I see mvc-dispatcher-servlet.xml. Why did eclipse not generate this xml file in my project?
[IMPORTANT] I wanted to set up strong security and user authentication for my web app. I have been following online tutorials again and they all create a seperate
xml file named spring-security.xml and add the namespace information to that file. Does it suffice if I just create this file and add the name space information? I mean
dont' I need to import this file to a main file that is scanned by Spring framework?
How do I define and where do I put spring application context.xml file and start wiring the dependencies together? Also if I define everything (all dependencies here) how is this file picked up by the framework?
Thanks,
Configuration Files
If you check your web.xml you will find both of root-context.xml and servlet-context.xml files being referred here. One used by Dispatcher Servlet and other by Context Loader Listenter. You can name your files to whatever unless they are being refereed in web.xml
Eclipse Not generating files
Every editor works its own way. some may generate full fledged project/app with both DispatcherServlet and ContextLoaderListner configured or some with only DispatcherServlet ( with minimal configutaion). Check Spring Roo it starts with basic and gives you the flexibility to generate a strong app.
mvc-dispatcher-servlet.xml is not there
Some of the thing in spring projects are convention based, for example if you are not providing any file to your DispatcherServlet in web.xml spring looks for mvc-dispatcher-servlet.xml file, and if you have provided it won't look for.
Spring Security
To Configure Spring Security you need to provide at least some configuration. But the question is where. You need to add this configuration to your web.xml only. and Hence no need to import this to any other file.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener- class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/spring-security.xml
</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Where to define application context.xml
Just define it any where, configure beans in it.
You can add this file as follows:
a) Either Import this into some other configuration file like root-context.xml or servlet-context.xml
as <import resource="application-context.xml"/>
b) Add this into web.xml with ContextLoaderListner as context param
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:META-INF/spring/application-context*.xml
classpath*:META-INF/spring/abc*.xml
</param-value>
</context-param>

About multiple containers in spring framework

In a typical Spring MVC project there two "containers": One created by ContextLoaderListener and the other created by DispatchServlet.
I want to know, are these really two IoC container instance?( I see two bean config files, one is root-context.xml the other is servlet-context.xml)
If there are 2 containers, then what's the relationship?
Can the beans declared in one container be used in the other?
From the Spring Official Website:
The interface org.springframework.context.ApplicationContext
represents the Spring IoC container and is responsible for
instantiating, configuring, and assembling the aforementioned beans.
The container gets its instructions on what objects to instantiate,
configure, and assemble by reading configuration metadata. The
configuration metadata is represented in XML, Java annotations, or
Java code.
Again from official Doc:
In the Web MVC framework, each DispatcherServlet has its own
WebApplicationContext, which inherits all the beans already defined in
the root WebApplicationContext. These inherited beans can be
overridden in the servlet-specific scope, and you can define new
scope-specific beans local to a given Servlet instance.
Now coming to your Question, as is stated here:
In Spring Web Applications, there are two types of container, each of
which is configured and initialized differently. One is the
“Application Context” and the other is the “Web Application Context”.
Lets first talk about the “Application Context”. Application Context
is the container initialized by a ContextLoaderListener or
ContextLoaderServlet defined in the web.xml and the configuration
would look something like this:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:*-context.xml</param-value>
</context-param>
In the above configuration, I am asking spring to load all files from
the classpath that match *-context.xml and create an Application
Context from it. This context might, for instance, contain components
such as middle-tier transactional services, data access objects, or
other objects that you might want to use (and re-use) across the
application. There will be one application context per application.
The other context is the “WebApplicationContext” which is the child
context of the application context. Each DispatcherServlet defined in
a Spring web application will have an associated
WebApplicationContext. The initialization of the WebApplicationContext
happens like this:
<servlet>
<servlet-name>platform-services</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:platform-services-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
You provide the name of the spring configuration file as a servlet
initialization parameter. What is important to remember here is that
the name of the XML must be of the form -servlet. xml.
In this example, the name of the servlet is platform-services
therefore the name of our XML must be platform-service-servlet.xml.
Whatever beans are available in the ApplicationContext can be referred
to from each WebApplicationContext. It is a best practice to keep a
clear separation between middle-tier services such as business logic
components and data access classes (that are typically defined in the
ApplicationContext) and web- related components such as controllers
and view resolvers (that are defined in the WebApplicationContext per
Dispatcher Servlet).
Check these links
Difference between applicationContext.xml and spring-servlet.xml in Spring Framework
http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/beans.html#beans-basics
There aren't two separate containers created. Typically, you want spring to instantiate the object declared in the servlet-context.xml when the object is required. So, you map the servlet-context.xml configuration file to the Dispatcher Servlet i.e. you want to initialize the object when a request hits the dispatcher servlet.
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Where as, if you want to initialize the object and perform action when the context is being loaded you would declare the configuration file with in the context-param tags of your deployment descriptor.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
You could test this out by writing by declaring separate beans in the servlet-context.xml and root-context.xml and then, autowiring them in a custom Context Loader Listener class. You would find only the root-context instances are initialized and servlet-context beans are null.
ApplicationContext a registry of components (beans).
ApplicationContext defines the beans that are shared among all the servlets i.e. root context configuration for every web application.
spring*-servlet.xml defines the beans that are related WebApplicationContexts here DispatcherServlet.
Spring container can have either single or multiple WebApplicationContexts.
Spring MVC have atleast 2 container -
Application Context declared by
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
Servlet context declared by -
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
And a web application can define any number of DispatcherServlet's. Each servlet will operate in its own namespace, loading its own application context with mappings, handlers, etc. Only the root application context as loaded by ContextLoaderListener, if any, will be shared. Thus can have any number of child containers.

ServletContext in Spring Application

I have one simple question.
If web.xml web application descriptor like this.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml,
/WEB-INF/anotherContext.xml,
/WEB-INF/another2Context.xml
</param-value>
</context-param>
ContextLoaderListener create three differents ServletContexts or three differents ServletContext childs inside one general parent ServletContext?
dispatcher-servlet.xml configuration of DispatcherServlet is another child than others three contexts above?
SOLUTION
I have been investigating about this area, I have created one example application, and every xml files from make one ServletContext only, the same root ServletContext application created by ContextLoaderListener.
maybe you can take a look at this old answer, have a great explanation.
Namespace vs contextConfigLocation Spring init parameters in web.xml
I hope it helps.

spring servlet-context in sts

Using STS in eclipse to create an mvc project I notice that the servlet-context.xml seems to be written to be used in both the root context and the dispatcherservlet Context. I say this because I notice that the context:component-scan is in it, which is often loaded into the root context, but it is loaded into the dispatcherservlet context. I also noticed a sample spring mvc/jpa project - http://duckranger.com/2012/04/spring-mvc-3-x-with-sts-tutorial-part-iii-add-some-jpa/ - that specifically loads the servlet-context.xml into both contexts. I thought the idea was to keep a clean separation between the contexts. Can someone explain this to me?
The following configuration is plain wrong
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:META-INF\root-context.xml
classpath:META-INF\servlet-context.xml
classpath:META-INF\datasource.xml
</param-value>
</context-param>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:META-INF\servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Your root and servlet context should NEVER import the same files, as the beans from the root context will already be available in the servlet context because of the context hierarchy in Spring. There is no point to create copies of them in the different contexts(especially because the beans in the root context will be shadowed by the ones in the servlet context, for example if you declare <tx:annotation-driven> only in the root context it will not affect the behavior of the servlet context beans, which will force you to tangle configuration even more) .
It's very illogical to put <jpa:repositories> into the servlet context, because it's VERY likely that you will use the repositories from the service layer.
Typically you should not put anything but the MVC configuration to the servlet context. It's the root web app context where the services should live. Servlet context provides separation of the controllers from the services, so when you test your services with Spring Test Context framework you don't have to create the controllers(if you want to test the mappings you should use Spring MVC Test framework) and test the application services directly.
To be clear, if we examine the figure from the Hexagonal Architecture article
the the servlet context should contain only user-side API related things but not the application. It is arguable whether you should divide the configuration of the root web app context and put data-side-api into separate configuration file but the question was about servlet/root contexts.
Just to be less abstract here's some informal diagram of what I typically keep in mind(in terms of Spring contexts and bean configuration files) when configure a Spring application(of course it's all subjective, it's not a super solution and actually is a bit over complicated - it's unlikely that I will need so many servlets and configuration files)

java.lang.IllegalStateException: Root context attribute is not of type WebApplicationContext

I am deploying Portlets on Liferay 5.2.3 on Tomcat 6. I get this error only for one of the portlet.
java.lang.IllegalStateException: Root context attribute is not of type WebApplicationContext
I did some research and found out that Spring was instantiating a portlet application context when it need a web one. But in my web.xml I am only defining contextLoaderListner
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
And to top it off, if a different *.jar file was being looked up by Spring, then why would my other portlets get deployed except one?
After couple of redeployments I get that to a fix. Can someone put some light on?
The root cause seems to be a static variable in the portal/application server "hanging onto" an instance of a class from the portlet. Two common culprits are log4j and java logging, both of which are commonly used by application containters.
See log4j and the thread context classloader and http://logback.qos.ch/manual/loggingSeparation.html for more discussion of loggers. The suggestion is to use SLF4J with logback OR to be sure to put log4j.jar in your WAR file so it is in the right classloader (although some containers will thwart this solution).
Also, some other class that is present in the container may be the cause. Logging is just a common problem.
Sounds like you are not defining the contextConfigLocation? in web.xml you should also have something like this in addition to the contextLoaderListener:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Where applicationContext.xml is a normal config file for a webapp.
You should also have this in your web.xml if using spring portlet MVC:
<servlet>
<servlet-name>ViewRendererServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ViewRendererServlet</servlet-name>
<url-pattern>/WEB-INF/servlet/view</url-pattern>
</servlet-mapping>
In your portlet.xml I guess you have something like this to specify your portlets:
<portlet>
<portlet-name>sample</portlet-name>
<portlet-class>org.springframework.web.portlet.DispatcherPortlet</portlet-class>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>view</portlet-mode>
</supports>
<portlet-info>
<title>Sample Portlet</title>
</portlet-info>
</portlet>
If you haven't already, see the spring portlet mvc reference documentation
Hope it helps.

Resources