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.
Related
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.
I have created a custom annotation in my spring mvc project.
The annotation is used to do an AOP
#Around("execution(#Cached * * (..)) && #annotation(cache)")
Here the annotation that I have created is "Cached", any method with the annotation is cached in couch base with the response as its value and the method argument as its key.
The problem is the annotation works (AOP works) on the controllers well. However from controllers, I am making call to different callable classes and utils. When I add the annotation" #Cached" on the callable classes or the util funcations the AOP doesn't work.
In the XML file, the following is what I have declared.
<aop:aspectj-autoproxy/>
<context:spring-configured/>
<context:component-scan base-package="com.abc.xyz">
<!--<context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>-->
</context:component-scan>
<bean id="universalController" class="com.abc.xyz.misc.UniversalController"/>
<bean class="com.abc.xyz.api.metric.SystemTiming"/>
<bean class="com.abc.xyz.api.annotations.URLCacheImpl"/>
With Spring AOP, your classes which match the pointcut (where you have placed your #Cached annotation in this specific case) should be Spring beans. So the best guess that I can make is that your utility classes are very likely not Spring beans and that is reason why they are not getting woven in. You have two options that I can think of:
Make your utility classes also clean Spring beans
Use full Aspectj support - this way even though your utility classes are not Spring beans they would be woven with the advice.
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
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
I just faced,that in order to use specific annotations for Spring Security, I should explicitely allow them in my config(applicationContext.xml)
Example:
<sec:global-method-security secured-annotations="enabled" />
<sec:global-method-security jsr250-annotations="enabled" />
...
What advantages do you see in approach of explicitely declare what annotations are allowed in our frameworked application?
Looks like overconfiguration,isn't it?
One possible benefit is that it allows Spring Security to throw an exception when desired annotations are not present in the classpath (though it's mostly about JSR-250 annotations, since other annotations are parts of Spring Security itself).
Otherwise Spring Security would have to silently ignore absence of annotations, that may lead to surprising behaviour.