Spring MVC: Does this code make child-parent relationship between two context? - spring

I have learned how to configure spring MVC without web.xml and .xml files for parent and child context from this link. I saw how to programmatically make context hierarchy in the official spring docs as follow.
ApplicationContext parent = new GenericXmlApplicationContext(ParentAnnotationConfig.class);
GenericApplicationContext child = new GenericApplicationContext(parent);
But the post from the link don't have similar statements like above ones. Does this code make context hierarchy between two context or not?

The code from the link you submitted uses Spring MVC. The programmatic method you show is independant of Spring MVC. It makes a big difference.
Spring MVC automagically creates parent child relations between the root context and the dispatcher servlet context(es). The wepapp should have :
one single root context referenced in the ServletContext. It is supposed to be used for everything not directly related to the servlet : model, persistance and filters that can exist independantly of the servlet
one context per dispatcher servlet constructed with the root context as parent. It is supposed to be used for controllers, views, interceptors
The parent-child relation ensure that you can access all beans from the controllers, but you cannot access web (servlet) beans from root contex.
To directly answer your question, I would say that the linked code does not explicitely build the context hierachy. The hierarchy is built by Spring MVC framework. So it does exist, and you must not try to generate it explicetely.

Related

DispatcherServlet and ContextLoaderListener in Spring

What is the difference between DispatcherServlet and ContextLoaderListener in Spring framework? Do we need to configure both of them in web.xml when we are using spring framework?
AFAIK each DispatcherServlet will have a WebApplicationContext. By default the DispatcherServlet looks for a spring configuration file named [appname]-servlet.xml under WEB-INF folder.
Do we need to configure DispatcherServlet?
Yes, every spring application should configure DispatcherServlet as it is the one through which all the requests are routed. It decides the appropriate method of the controller class to handle the request. Once controller returns the model along with the logical view, DispatcherServlet takes the help of ViewResolver to resolve the view (generally JSPs) and will pass the model data to the view, which is finally rendered on the browser.
Do we need to configure ContextLoaderListener?
No, this is not mandatory. Spring applications can live with out ContextLoaderListener.
Why do we need ContextLoaderListener?
Usually when we build multi-tier applications we don't want to clutter all the beans in one config file [appname]-servlet.xml. For example if you configure spring security you wanted to include all those beans in security-context.xml, in the same way all the beans belonging to service layer are configured in applicationContext.xml and some would like to configure beans belonging to DAO layer in dao-context.xml. So when you configure all these beans in different context files, you need to let know spring that these files exist as spring only knows about [appname]-servlet.xml. ContextLoaderListener will help spring recognize all the other context files.
Hope this helps!
The root WebApplicationContext is a Spring Application Context shared across the application.
A DispatcherServlet instance actually has its own
WebApplicationContext.
One can have multiple DispatcherServlet instances in an application, and each will have its own WebApplicationContext.
The root WebApplicationContext is shared across
the application, so if you have a root WebApplicationContext and
multiple DispatcherServlets, the DispatcherServlets will share the
root WebApplicationContext.
However, for a simple Spring MVC application, one can even have a situation where there is no need to have a root WebApplicationContext. A DispatcherServlet would still have its own WebApplicationContext, but it doesn’t actually need to have a parent root WebApplicationContext.
So, which beans should go in the root Web Application Context and which beans should go in the DispatcherServlet’s Web Application Context?
Well, general beans such as services and DAOs make their way in root Web Application Context, and more web-specific beans such as controllers are included in DispatcherServlet’s Web Application Context.
When DispatcherServlet starts up, it creates a Spring application context and starts
loading it with beans declared in the configuration files or classes that it’s given.
But in Spring web applications, there’s often another application context. This
other application context is created by ContextLoaderListener
Whereas DispatcherServlet is expected to load beans containing web components
such as controllers, view resolvers, and handler mappings, ContextLoaderListener is
expected to load the other beans in your application. These beans are typically the
middle-tier and data-tier components that drive the back end of the application.
Good luck!

Servlets in spring mvc

I have fundamental idea about servlet and spring mvc. But I don't know that there is a usage of servlets in spring mvc or not. In spring mvc we have controller classes. My thinking is servlet is used in spring mvc as a controller. If I'm incorrect please correct me.
Yes,you are perfectly right. Servlets are used in Spring-MVC. In Spring-MVC when you write annotation like #Controller, indirectly you are using a Servlet called Dispatcher Servlet. Dispatcher Servlet is defined in web.xml file with properties and class name which is mapped to .jsp pages and Controller part.
Related / Duplicated to When to use Servlet or #Controller. The question is not the same but quite the explanation on that question you will be able to understand:
If you're a student interested in learning the language then I would stick with servlets for now. It's possible to write a web app using just servlets but in practice you'll probably want to look at JSP's too.
A JSP is a convenient way to write a servlet that allows you to mix html with scripting elements (although it's recommended to avoid Java code in your jsp in favour of tags and el expressions). Under the covers it will be compiled as a servlet but it avoids you having to use lots of messy print statements.
It's important to have at least a basic understanding of servlets and JSP's. Spring MVC is one of many frameworks built on top of servlets to try make the task of writing a web application a bit easier. Basically all requests are mapped to the DispatcherServlet which acts as a front controller.
The DispatcherServlet will then call the controller whose annotations match the incoming request. This is neater than having to write these mappings yourself in the web.xml (although with servlet 3.0 you can annotate servlets now). But you also get many other benefits that can be used like mapping form fields to an object, validating that object with jsr303 annotations, map inputs and outputs to xml or json etc etc. Plus it's tightly integrated with core spring so you can easily wire in your services for the controller to call.
It's worth noting that there are a plethora of competing frameworks built on top of servlets. Spring MVC is one of the most popular so it's not a bad choice to look into.
Controllers are not Servlets! Controllers are normal Spring MVC beans that do not extend HttpServlet. Instead what Spring has is a custom extension of HttpServlet called DispacherServlet. Looking at the DispacherServlet's source code you can see that the class hierarchy goes: DispatcherServlet extends FrameworkServlet → FrameworkServlet extends HttpServletBean → HttpServletBean extends HttpServlet.
The DispatcherServlet, like any other Servlet, is declared in the web.xml. It handles all incoming HTTP requests. It is called a front controller which provides a single point of entry in your application. It is responsible for request handling by delegating requests to additional components of Spring MVC controllers which do not extend the HTTP Servlet API.
Look at the following diagram
In this picture DispacherServlet is the only HttpServlet. The Controllers, HandlerMapping and ViewResolver are all Spring MVC beans.

Application context and spring context is same?

I am new to spring MVC,and just started working on it.I would like to know about the application context(web-applicationcontext) and the context provided by the spring i.e spring-servlet.xml whether it is same or different.
Hopefully somebody could give me the greater idea to come over this confusion.
The difference between the application context and servlet context is that whatever is specified in the application context can be referenced in the servlet context, but not vice-versa.
That's to say that you can have components that are reused through your servlets specified at the application context level, but certain things that are only specific to a certain servlet can be specified there to isolate them from the application and other servlets.
That's there if you have a need for fine-grained control.
You can treat them as being the same file. Look at this answer for more details.
The application-context provided by *-servlet.xml is the WebApplicationContext see here for more info on this. The root application is created by the contextLoader listener .
Quoting from the Spring reference,
"In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext.
The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes (see Section 15.7, “Using themes”), and that it knows which servlet it is associated with (by having a link to the ServletContext). The WebApplicationContext is bound in the ServletContext, and by using static methods on the RequestContextUtils class you can always look up the WebApplicationContext if you need access to it."
You can find the details of the root Application context here

Spring-MVC: What are a "context" and "namespace"?

From XmlWebApplicationContext javadoc:
By default, the configuration will be taken from "/WEB-INF/applicationContext.xml" for the root context, and "/WEB-INF/test-servlet.xml" for a context with the namespace "test-servlet" (like for a DispatcherServlet instance with the servlet-name "test").
What does it mean a Spring context?
What is the root context? What other kinds of Spring context are there?
What is a namespace?
UPDATE:
Some follow-up questions:
What is a Spring ApplicationContext - is it some "thing" that holds the beans that are defined in a configuration XML file?
Looking at the code of ContextLoaderListener, it looks like it loads the data defined in the config XML file(s). But my Spring web app works without defining this listener or any other listener. How could it be?
In what scenarios would it make sense to have more than one instance of Spring's DispatcherServlet?
Is the root context (data from applicationContext.xml) applicable to every instance of DispatcherServlet, while other contexts (e.g. data from test-servlet.xml) applicable only to the relevant DispatcherServlet (i.e. test)?
"Spring context" = a Spring ApplicationContext.
"root context", in terms of a web application, means the main context that's loaded and used by the webapp. Typically, you'll start the root context with a ContextLoaderListener.
The root context isn't really a "kind" of context. It's just a role that a context plays. You have one root context in a webapp. Other contexts are not the root context. They're usually children of the root context.
A namespace here refers to the scope of an instance of Spring's DispatcherServlet. All it's saying right there is that if you name your servlet "test" in your web.xml, then by convention, Spring will look for a file named "test-servlet.xml" to use as that dispatcher's context. Incidentally, each context like this which is created for a dispatcher becomes a child of the root context.
Edit: To answer your new questions:
Follow the link in the first line of my answer to learn about the ApplicationContext. If you have questions not answered there, I'd suggest posting a new SO question.
The root context is optional. If you don't have the ContextLoaderListener defined, then you just don't have a root context. When you use a DispatcherServlet, it starts its own ApplicationContext, and it will get the beans it needs from there.
I don't know of one off the top of my head. I suppose if there were a need for drastically different configurations between some of the URL resources in your app, that might drive you to do it.
Yes. To state it in the proper terms, the root context is the parent context of any context started for a DispatcherServlet. Beans in a parent context are accessible through and by the child context, but the reverse isn't true.
In a web application, the architecture is usually divided into layers like the popular MVC structure.
So a web app comprises basically of a layer that handles the client requests i.e HTTPRequests
and a layer that services those requests .
To summarize : classes that are meant to handle the Http requests i.e the controllers which are mapped to urls come under the test-servlet.xml. This is called as WebapplicationContext containing only the beans that are required mainly to handle the client requests.
Now the next part is the Service/Dao layer that comprises of your business logic. Beans that perform such logic are loaded under ApplicationContext object.
Now you may ask why have they separated these things in to files or two different objects.
Its because, an application have the same business logic that can be used by multiple clients working on different protocol. You may use the same service layers to handle RMI as well as HTTP calls.
So Spring created a parent context that is started us as an ApplicationContext. And then if your applicationhandles web requests, you can create a dispathcher servlet which has its own Webapplicationcontext and initialized as a child of the parent context.
So all the parent beans can be referenced in the child and can be overiden but not vice versa

Why use Spring ApplicationContext hierarchies?

I am trying to understand ApplicationContext hierarchies in spring.
I learned the following
An ApplicationContext cannot have
more than 1 parent
ApplicationContext.
When a given
ApplicationContext cannot resolve a
bean, it will pass on the resolution
request to its parent.
The parent of
an ApplicationContext is specified
in its constructor.
I would like to understand when to use ApplicationContext hierarchies (instead of a single ApplicationContext).
The best I could get from google was this. And what I understand is that if an application has a large number of beans defined at the various layers then each layer having its own ApplicationContext would be a benefit. What is not understood is what is the benefit of doing so and how is the benefit achieved?
The classic use-case for this is when you have multiple Spring DispatcherServlet within a single webapp, with each of these servlets having their own app context, but which need to share beans between them. In this case, you add a 3rd context at the level of the webapp, which is the parent of each of the servlet appcontexts.
You can take this pattern further, for example if you have multiple webapps bundled into a single JavaEE EAR. Here, the EAR can have its own context, which is the parent of the individual webapp contexts, which is the parent of the servlet contexts, and so on. You have this hierarchy of responsibility.
In other situations, the context structure is dictated by some other factor. For example, Spring Security is independent of Spring MVC, and requires its configuration beans to go in the webapp context. If you want to use Spring MVC with it, then the config for that has to go into the servlet context, which has the root webapp context as its parent.

Resources