context:component-scan takes more than 2 minutes to complete - spring

I am new to springs. I tried using context:component-scan to scan my package like
<context:component-scan base-package="org.example">
However it seems very time consuming and takes more than 2 minutes. Is there a way to improve its performance

If you have a lot of classes it's normal to take that long. Most likely you also scan some classes that should not be scanned. You can optimise it by scan only the packages you need. for example if you have annotated controlers you can scan only the package witch contains them. <context:component-scan base-package="org.example.web.controller">.

You can also use <context:include-filter /> and <context:exclude-filter /> elements within the <context:component-scan /> element to further limit the scope of the scan.

Are you building an app using Spring MVC?
Mostly developers make the mistake of loading the beans twice by scanning the same thing in application-context and *-dispatcher-servlet.xml.
Am thinking out load, in your web.xml you must have loaded a context using contextloaderlistener and declared a SpringDispatcher servlet.
Just make sure that you only load the controllers beans inside *-servlet.xml file.
Your server layer(service and dao classes) should be loaded from the files you load via contextloaderlistener.
Like Jukka mentioned, you can avoid this by using exclude filter on #Controller annotation in the application-context.xml

Related

duplication in parsing spring context

Nowadays I've got to know spring mvc.
exactly about
context:component-scan
and
mvc:annotation-driven
and
tx:annotation-driven
in spring config xml
Here is my question.
As I know, "context:component-scan" scans all beans.
and As I heard, mvc:annotation-driven, tx:annotation-driven"s also scan all beans.
I think this is not efficient and not reasonable.
Why scan twice, three times.
Is there any way to avoid this duicate parsing?
Any answer will be appreciated.
Thank you.
In my opinion, scanning process are not twice, three times as you think.
They are declare for related beans I think.
Please refer to below summarize and find out how differences.
<context:annotation-config>
Declares support for general annotations such as #Required, #Autowired, #PostConstruct, and so on.
<context:component-scan>
can also do what <context:annotation-config> does but <context:component-scan> also scans packages to find and register beans within the application context.
<mvc:annotation-driven />
Enables the Spring MVC #Controller programming model and
declares explicit support for annotation-driven MVC controllers (i.e. #RequestMapping, #Controller, although support for those is the default behaviour), as well as adding support for declrative validation via #Valid and message body marshalling with #RequestBody/ResponseBody.
<tx:annotation-driven />
You do provide the transaction-manager instace directly within element. annotation-config and component-scan won't.

Can I autowire (and autodiscover) daos while specifying the entities through a hibernate config?

Basically, I have objects that need to become entities, but the code is generated and I can't touch it (thus I can't use annotations). I'd like to list them in an xml config. However, I'd also like spring to autodiscover and autowire the respective daos. How would I go about setting up my configuration?
You can configure the component scan how you like (btw: you can have several component scans)
<context:component-scan base-package="org.example" use-default-filters="false">
<context:include-filter type="regex" expression=".*Dao"/>
</context:component-scan>
This example will create beans for all classes thet match the regex and are located within the base package.
#See Spring Reference Chapter 3.10.3 Using filters to customize scanning

Different Spring Annotation XML Declarations

There seem to be multiple XML tags for telling Spring to use annotations:
<context:annotation-config/>
<context:component-scan base-package="org.example" />
<mvc:annotation-driven />
<tx:annotation-driven transaction-manager="transactionManager" />
I think the first tag says to scan for annotations, the second says which package to scan (and optionally, can exclude/include what to search for). Then maybe the third says to scan for controller classes. And the last one to scan for data access annotations.
My problem understanding is:
I would think tags 1 and 2 could be combined into one. So I don't know why they are separated.
Tags 3 and 4 seem redundant to 1 and 2.
Could anyone give me a breakdown of what each tag does, and why they're not redundant? And if there are any other annotation XML tags, let me know.
EDIT
After further investigation, I believe I found some additional information:
The <context:annotation-config/> tag allows you to use annotations on variables, constructors, and methods (e.g. #Autowired, #Resource, etc).
The <context:component-scan base-package="org.example" /> tag allows you to use annotations on classes (e.g. #Repository, #Controller, etc).
The <tx:annotation-driven transaction-manager="transactionManager" /> tag actually enables the #Transactional tag (the <context:annotation-config/> tag allowed the #Transactional tag, but it didn't do anything).
Still not completely sure on the <mvc:annotation-driven />. I think maybe it adds further support for JSON, etc.
Difference between annotation-config and component-scan
a) <context:annotation-config/> only looks for annotations on beans in the same application context in which it is defined. This means that, if you put <context:annotation-config/> in a WebApplicationContext for a DispatcherServlet, it only checks for #Autowired beans in your controllers, and not your services. See Section 15.2, “The DispatcherServlet” for more information.
b) Spring provides the capability of automatically detecting 'stereotyped' classes and registering corresponding BeanDefinitions with the ApplicationContext. To autodetect these classes and register the corresponding beans requires the inclusion of the component-scan element in XML where 'basePackage' would be a common parent package (or alternatively a comma-separated list could be specified that included the parent package of each class).
tx:annotation-driven
You do provide the transaction-manager instace directly within element. annotation-config and component-scan won't.
mvc:annotation-driven
This tag registers the DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter beans that are required for Spring MVC to dispatch requests to #Controllers. The tag configures those two beans with sensible defaults based on what is present in your classpath. Read more at Spring doc.
I would think tags 1 and 2 could be combined into one. So I don't know why they are separated.
For reasons of backwards compatibility. Old Spring apps have to keep working, and merging the tags (which were introduced in different versions of Spring) would break that by changing the default behaviour.
Tags 3 and 4 seem redundant to 1 and 2.
See above. The 4 tags do slightly different, but complimentary things. Yes, if Spring were designed from scratch, there would be fewer of them, but the functionality needs to remain seperate.
To summarise:
<context:annotation-config/> enables annotation support in the context. This was added as part of Java 5 support, at a time when Spring still supported Java 1.4
<context:component-scan base-package="org.example" /> enables automatic scanning and configuration of beans, instead of using explicit declarations. This was added in Spring 2.5.
<mvc:annotation-driven /> is an odd one. It is not required in order to support annotated controller (those work by default). What it does is to actually disable the old style of non-annotated controller, as well as adding support for things like JSON. This is required because older apps still use the older controller style.
<tx:annotation-driven> is required because Spring supports many different styles of transaction demarcation, one of which is the annotation style. This is most popular style, but by no means the only one.

Spring XML file configuration hierarchy help/explanation

When I first started learning about Spring, things were configured in the applicationContext.xml file. Then as I started to read books specifically on more recent versions of spring, they've all done the configuration in separate XML files such as myapp-servlet-xml, myapp-security.xml, myapp-service.xml, etc., by configuring a contextConfigLocation in the web.xml file. So, for instance, the code I've been following along with had this as it's contextConfigLocation:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/myapp-servlet.xml
/WEB-INF/myapp-data.xml
</param-value>
</context-param>
Anyway, recently I ran into a configuration issue (which the helpful people here at StackOverflow helped me figure out) that was due to this separation. There was no applicationContext.xml file for the examples from these books and later on when I tried adding automatic scanning and annotations to the app this caused issues. I tried moving everything into applicationContext.xml and doing away with the other files and that solved the problem. Nothing else changed, I just put everything in applicationContext.xml.
So, this, along with comments from others, has lead to me sort of understand that even if you don't create an applicationContext.xml, it's still being used and it is the top level of some sort of configuration hierarchy. I'm hoping someone else can explain to me how this all works because I've not come across any explanation on it anywhere.
So for example, if I put certain context:component-scan tags into configuration files that are below applicationContext.xml, it could cause certain classes to not get scanned. Things of that nature. I don't understand the precedence and what has to go where to be sure it's seen application wide and so on. If anyone can clearly explain it or point me to a resource that explains it I would much appreciate it, thank you. Hopefully what I'm asking makes sense.
There's nothing special about the file named "applicationContext.xml" except that it's the name Spring tends to expect as its default configuration file. Using one file named that or multiple files named "dog.xml", "cat.xml", and "alien.xml" will work exactly the same way. The trouble you're having comes from having multiple ApplicationContexts in use at the same time, not from having multiple XML files. I've recently answered a couple of questions from people who had problems caused by not understanding these concepts. Check out those answers, and see what questions you still have:
Declaring Spring Bean in Parent Context vs Child Context
Spring-MVC: What are a "context" and "namespace"?
Edit: In response to your new question:
I had a <context:component-scan base-package="com.myapp"/> tag in my servlet.xml.
I'm guessing this "servlet.xml" file is named like foo-servlet.xml, where the DispatcherServlet configured in your web.xml is named "foo", like
<servlet>
<servlet-name>foo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
By convention, when this DispatcherServlet starts, it'll create a new ApplicationContext that's configured by the file foo-servlet.xml, derived from the servlet-name. Now, since you put a context:component-scan in there, it's going to recursively scan the given package and create beans for all annotated classes. The package you gave it, com.myapp, looks like it's the base package for your entire app, so Spring will create beans from all of the annotated classes in your app, including the data access ones, in this one ApplicationContext that's associated to the DispatcherServlet. Typically, this context should only have view-layer stuff and beans that directly support the DispatcherServlet in it, so this was something of a misconfiguration.
In my data.xml file I had data source beans and that was it. No other beans, everything else was autowired and annotated.
Presumably, this "data.xml" file is the one you listed in the contextConfigLocation context-param. Assuming you'd also added the ContextLoaderListener to your web.xml, like
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
then that file will be used to create a second ApplicationContext--the root context. That's what this listener does. Note that it actually builds the context from all the files listed in contextConfigLocation, and if you also included your "servlet.xml" in that list, then you've loaded that config twice: here in the root context as well as in the context associated with the DipatcherServlet. Hopefully you see now how there's a distinct division between the XML configuration files and the ApplicationContexts that they configure. The same XML file can easily be used to configure two different contexts. Whether doing so is correct or not is another question. In this particular case, it isn't.
The order I've described these two contexts in is actually backwards. I was just following your description of what you did. The ContextLoaderListener, being a ServletContextListener, will always execute before any servlet starts up. This means the root context is created first, and the other context second. This is by design so that when the DispatcherServlet creates its context, it can add that context as a child of the root context. I've described this relationship in those other posts. The most important effect of this is that beans in the root context are available to and via the DispatcherServlet's context. That applies to autowired relationships, too. That's important because the DispatcherServlet only looks in its associated context for beans that it needs, like controller instances. Your controllers, though, obviously have to be wired with supporting beans. Thus, traditionally, the controllers live in the DispatcherServlet's context, and the supporting beans live in the root context.
I then tried to add #Transacational to my service bean and it wouldn't persist.
In order for #Transactional to work, you must include the <tx:annotation-driven/> tag in the configuration of the ApplicationContext where the annotated bean lives. The trick is figuring out the "where it lives" part. Beans in a child can override beans in a parent context. Therefore--I'm just guessing here--if you loaded all your beans into the DispatcherServlet context as I described above but put the <tx:annotation-driven/> in the root context, you might have a bean in the root context that's correctly transactional, but it's not the one being used because the duplicate is "closer" to the servlet in the parent/child hierarchy, and the context it's in didn't get a <tx:annotation-driven/> configuration.
When I changed the servlet context:component-scan tag to instead point at com.myapp.web and then added a context:component-scan tag to the data.xml file, everything worked.
It still depends somewhat on exactly which config files you were including in which ApplicationContexts, but at the very least I can say that by doing this, you removed a lot of beans from the DispatcherServlet's context which were causing problems. In particular, your correctly-configured #Transactional beans in the root context would no longer be shadowed by beans in the child context and would be injected into your controllers, so your persistence stuff would work then.
So... the main thing to take away is that you have two related ApplicationContexts. You have to remain aware of that fact and stay in control of which beans go in which context.
Does that cover everything?

spring context:component-scan not working

I have two packages holding spring controllers,I am not able to give actual names and packages.
com.test.controller------ABCController
com.test.xyz.controller------xyzController
I defined <context:component-scan base-package="com.test"/> in spring xml file,Spring able to find out controllers from com.test.controller,XYZController never called from spring container.it is saying no handler found.If i move xyzcontroller under package com.test.controller,then it's start working.
Please give any hints,why XYZController not working.
Thanks,
Raj
Use <context:component-scan base-package="com.test.**"/> in your spring config, so it will scan for every annotated class in all subpackages of com.test.

Resources