Use annotation to reduce spring bean Configuration

Source: Internet
Author: User

This article from: http://blog.csdn.net/dqatsh/article/details/3478000

I found a good article http://www.ibm.com/developerworks/cn/java/j-lo-spring25-ioc/ which gives a more detailed description than this article.

Springframework 2.5 introduces a complete annotaion configuration annotation. Using these annotation can greatly reduce bean definitions and make Program Development easier and easier to maintain.

Of course, you need to use Java 5 or later to use annotation.

Define a bean using annotaion
@ Component is a general annotation used to indicate that a class is a spring container management class.
In addition, @ controller, @ service, and @ repository are refined by @ component. These three annotations have more semantics than @ component, they correspond to the class of the presentation layer, service layer, and persistence layer respectively.
If you only use them to define beans, you can only use @ component. However, since spring provides these refined annotations, it is certainly advantageous to use them, but not in the following examples.

Defines an Interface

  1. Package test1;
  2. Interface moviefinder {
  3. String getdata ();
  4. }

Define an implementation

  1. Package test1;
  2. Import org. springframework. stereotype. repository;
  3. @ Repository
  4. Public class jpamoviefinder implements moviefinder {
  5. @ Override
  6. Public String getdata (){
  7. Return "this is jpamoviefinder implementation! ";
  8. }
  9. }

The annotation @ repository is used here, indicating that this is a bean definition managed by the spring container. This annotation does not specify the bean name. The default value is the class name starting with lowercase, that is, jpamoviefinder, if you want to specify a name, you can write @ repository ("mymoviefinder ").
Here you can also use the @ component annotation, which does not demonstrate the benefits of @ repository.
The scope of this bean is not specified here. The default value is Singleton. If you want another scope, you can use the annotation @ scope.

  1. @ Scope ("prototype ")
  2. @ Repository
  3. Public class moviefinderimpl implements moviefinder {
  4. //...
  5. }

Spring scans and registers annotation beans
Jpamoviefinder only adds an annotation, which is not automatically registered to the spring container. We need to tell the spring container to look for these beans there.
The configuration is as follows:

  1. <? XML version = "1.0" encoding = "UTF-8"?>
  2. <Beans xmlns = "http://www.springframework.org/schema/beans"
  3. Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
  4. Xmlns: context = "http://www.springframework.org/schema/context"
  5. Xsi: schemalocation = "http://www.springframework.org/schema/beans
  6. Http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  7. Http://www.springframework.org/schema/context
  8. Http://www.springframework.org/schema/context/spring-context-2.5.xsd>
  9. <Context: component-scan base-package = "test1"/>
  10. </Beans>

<Context: component-scan base-package = "test1"/> This configuration tells the spring container to scan all classes in the package test1 to find the class to be annotated.
Since not all classes in test1 have annotations, the efficiency of all traversal is not high, so spring defines the filter to reduce the scanning range, which is not used for the sake of simplicity.

Use annotations for dependency Injection

  1. Package test1;
  2. Import org. springframework. Beans. Factory. annotation. autowired;
  3. Import org. springframework. stereotype. Service;
  4. @ Service
  5. Public class simplemovielister {
  6. @ Autowired
  7. Private moviefinder;
  8. Public String getdata (string name ){
  9. Return "hi" + name + "! "+ Moviefinder. getdata ();
  10. }
  11. Public moviefinder getmoviefinder (){
  12. Return moviefinder;
  13. }
  14. Public void setmoviefinder (moviefinder ){
  15. This. moviefinder = moviefinder;
  16. }
  17. }

Simplemovielister is a service class. It also uses @ service annotation for bean. This class uses moviefinder. In order to inject the implementation of this class, annotations are used here.@ Autowired, The spring container will automatically find the appropriate bean injection. Note that the name of the injected bean is not specified here, Because spring only finds one implementation, that is, jpamoviefinder. Later, we will see two implementations.

Note: When the above Code uses @ autowired, the public void setmoviefinder (moviefinder) method is not required. You can delete it for a try. If you use the xml configuration method, this method must exist. I keep this method here for the hybrid use of the following test annotation and xml configuration.

Test 1

  1. Package test1;
  2. Import org. springframework. Context. applicationcontext;
  3. Import org. springframework. Context. Support. classpathxmlapplicationcontext;
  4. Public class main {
  5. Public static void main (string [] ARGs ){
  6. Applicationcontext context = new classpathxmlapplicationcontext ("test1/beans. xml ");
  7. Simplemovielister M = (simplemovielister) Context. getbean ("simplemovielister ");
  8. System. Out. println (M. getdata ("Arthur "));
  9. }
  10. }

Hi Arthur will be printed on the console! This is jpamoviefinder implementation!

Added the second implementation of moviefinder.

  1. Package test1;
  2. Import org. springframework. stereotype. repository;
  3. @ Repository
  4. Public class ibatismoviefinder implements moviefinder {
  5. @ Override
  6. Public String getdata (){
  7. Return "this is ibatismoviefinder implementation! ";
  8. }
  9. }

When you run main, the system reports an error:
Exception in thread "Main" org. springframework. beans. factory. beancreationexception: Error creating bean with name 'simplemovielister ': injection of resource fields failed; Nested exception is Org. springframework. beans. factory. nosuchbeandefinitionexception:
No unique bean of Type [test1.moviefinder] is defined: Expected single matching bean but found 2: [jpamoviefinder, ibatismoviefinder]
The error message shows that moviefinder has two bean implementations: jpamoviefinder and ibatismoviefinder. The spring container does not know which bean to use. In this case, you can use the annotation @ qualifier to specify the specific bean.

  1. //...
  2. @ Service
  3. Public class simplemovielister {
  4. @ Autowired
  5. @ Qualifier ("ibatismoviefinder ")
  6. Private moviefinder;
  7. //...

Here we specify to inject the ibatismoviefinder bean.
Run main. The console will print Hi Arthur! This is ibatismoviefinder implementation!

Injection annotations provided by Java 6
Spring can also use the @ resource annotation provided by Java 6 to specify which bean to inject.

  1. //...
  2. @ Service
  3. Public class simplemovielister {
  4. @ Resource (name = "ibatismoviefinder ")
  5. Private moviefinder;
  6. //...

This is consistent with the @ autowired function.

Annotation or XML
Annotations are easy to use, but we can also see the annotation problem from the above example. moviefinder has two implementations. simplemovielister specifies which implementation is used in the program with annotations. If you want to modify the annotation, you need to modify the source program. Therefore, annotations are only applicable to fixed dependencies. If the dependency needs to be adjusted during deployment, it is easy to use the xml configuration method. After all, you only need to modify the XML file.

In actual use, we can use both XML and annotation methods.

  1. <? XML version = "1.0" encoding = "UTF-8"?>
  2. <Beans xmlns = "http://www.springframework.org/schema/beans"
  3. Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
  4. Xmlns: context = "http://www.springframework.org/schema/context"
  5. Xsi: schemalocation = "http://www.springframework.org/schema/beans
  6. Http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  7. Http://www.springframework.org/schema/context
  8. Http://www.springframework.org/schema/context/spring-context-2.5.xsd>
  9. <Context: component-scan base-package = "test1"/>
  10. <Bean id = "simplemovielister1" class = "test1.simplemovielister">
  11. <Property name = "moviefinder" ref = "jpamoviefinder"/>
  12. </Bean>
  13. </Beans>

The xml configuration method is used to define another bean and inject the jpamoviefinder implementation.

  1. Package test1;
  2. Import org. springframework. Context. applicationcontext;
  3. Import org. springframework. Context. Support. classpathxmlapplicationcontext;
  4. Public class main {
  5. Public static void main (string [] ARGs ){
  6. Applicationcontext context = new classpathxmlapplicationcontext ("test1/beans. xml ");
  7. Simplemovielister M = (simplemovielister) Context. getbean ("simplemovielister ");
  8. System. Out. println (M. getdata ("Arthur "));
  9. Simplemovielister M1 = (simplemovielister) Context. getbean ("simplemovielister1 ");
  10. System. Out. println (m1.getdata ("Arthur "));
  11. }
  12. }

Simplemovielister is from annotation, and simplemovielister1 is from xml configuration. Running result:
Hi Arthur! This is ibatismoviefinder implementation!
Hi Arthur! This is jpamoviefinder implementation!

It proves that hybrid use is feasible. You can continue the test and reconfigure simplemovielister with XML.
Therefore, even if I used annotations at the beginning, I regretted it. It doesn't matter. You don't have to modify the source program. how to configure XML in the past and how to configure it now.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.