Use Spring @ Configuration

Source: Internet
Author: User

Although Spring has provided more than a dozen annotations since the release of Version 2.0, the annotations are provided only to simplify the XML configuration in some cases, rather than replacing the XML configuration method. From the initialization class of Spring IoC container, we can see that the most common implementation classes of ApplicationContext interfaces are ClassPathXmlApplicationContext and FileSystemXmlApplicationContext, as well as XmlPortletApplicationContext for Portlet and XmlWebApplicationContext for web, they are all XML-oriented. Spring 3.0 adds two implementation classes: AnnotationConfigApplicationContext and AnnotationConfigWebApplicationContext. From the name, we can see that they are generated for annotations and directly rely on annotations as container configuration information to initialize the IoC container class. Because AnnotationConfigWebApplicationContext is a web version of AnnotationConfigApplicationContext, its usage is almost the same as that of the latter. Therefore, this article will take AnnotationConfigApplicationContext as an example to explain.

AnnotationConfigApplicationContext works with @ Configuration and @ Bean annotations. Since then, the XML Configuration method is no longer the only Configuration method for Spring IoC containers. There is a competitive relationship between the two within a certain range, but they are still in a cooperative relationship in most cases. The combination of the two makes the configuration of Spring IoC containers simpler and more powerful.

Previously, we concentrated the configuration information in XML. Now, with annotations, the vector of the configuration information is transferred from the XML file to the Java class. We usually end the class name used to store configuration information with "Config", such as AppDaoConfig. java and AppServiceConfig. java. We need to add the @ Configuration annotation to the class used to specify the Configuration information to explicitly indicate that this class is the source of Bean Configuration information. Spring has the following requirements for the Configuration class:

The configuration class cannot be final; the configuration class cannot be localized, that is, the configuration class cannot be defined inside the methods of other classes; the configuration class must have a no-argument constructor. AnnotationConfigApplicationContext identifies the return value of the @ Bean method in the configuration class as Spring Bean and registers it to the container, which is managed by the IoC container. @ Bean is equivalent to labels in XML configuration. Example:

@ Configuration

Public class BookStoreDaoConfig {

@ Bean

Public UserDao userDao () {return new UserDaoImpl ();}

@ Bean

Public BookDao bookDao () {return new BookDaoImpl ();}

}

When parsing the above files, Spring will identify all the methods marked with @ Bean, execute them, and register the return values of the methods (UserDaoImpl and BookDaoImpl objects) into the IoC container. By default, the Bean name is the method name. Therefore, the XML configuration equivalent to the preceding configuration is as follows:

  

  

@ Bean has the following four attributes:

Name -- specifies the name of one or more beans. This is equivalent to the name attribute in XML configuration. InitMethod -- after the container initializes the Bean, it will call the method specified by this attribute. This is equivalent to the init-method attribute in XML configuration. DestroyMethod -- this attribute is similar to the initMethod function. The method specified by this attribute is called before the container destroys the Bean. This is equivalent to the destroy-method attribute in XML configuration. Autowire -- specifies the automatic assembly policy for Bean attributes. The value is three static attributes of the Autowire type. Autowire. BY_NAME, Autowire. BY_TYPE, Autowire. NO. Compared with the value of the autowire attribute in XML configuration, constructor is missing because constructor has no meaning here. @ Bean does not directly provide the attribute of the specified Scope. You can use @ Scope to implement this function. The usage of @ Scope is listed above.

The following describes the annotation-based container initialization. AnnotationConfigApplicationContext provides three constructors for initializing containers.

AnnotationConfigApplicationContext (): This constructor initializes an empty container that does not contain any Bean information. You need to register the configuration class by calling its register () method later and call refresh () method to refresh the container. AnnotationConfigApplicationContext (Class... annotatedClasses): This is the most common constructor. By passing the involved configuration class to this constructor, the Bean in the corresponding configuration class is automatically registered to the container. AnnotationConfigApplicationContext (String... basePackages): This constructor automatically scans all classes in a given package and its sub-packages, automatically recognizes all Spring beans, and registers them to the container. It not only recognizes the Configuration classes marked with @ Configuration, but also recognizes the classes marked with @ Repository, @ Service, @ Controller, and @ Component. In addition to using the third type of constructor to enable containers to automatically scan Bean configuration information, AnnotationConfigApplicationContext also provides the scan () method, which is similar to the preceding method, this method is mainly used to dynamically add beans to the container after container initialization. After this method is called, you must call refresh () to refresh the container immediately.

Note that AnnotationConfigApplicationContext registers the Configuration class as a Bean when parsing the Configuration class, because @ Configuration annotation is marked by @ Component during its definition. Therefore, one @ Configuration is also one @ Component. In most cases, developers cannot use this Bean, and ideally, this Bean should be transparent to developers. @ Configuration is defined as follows:

@ Target ({ElementType. TYPE })

@ Retention (RetentionPolicy. RUNTIME)

@ Brief ented

@ Component

Public @ interface Configuration {

String value () default "";

}

In a general project, to ensure a clear structure, multiple XML configuration files are usually defined based on the software module or structure, and then a configuration file for the entry is defined, this file is used to organize other configuration files. Finally, you only need to pass the file to the ClassPathXmlApplicationContext constructor. Spring also provides similar functions for annotation-based configuration. You only need to define an entry configuration class and use the @ Import Annotation on the class to introduce other configuration classes, finally, you only need to pass the entry class to AnnotationConfigApplicationContext. Example:

@ Configuration

@ Import ({BookStoreServiceConfig. class, BookStoreDaoConfig. class })

Public class BookStoreConfig {... }

Bean configuration using XML and annotation in combination

The original intention of designing @ Configuration and @ Bean is not to completely replace XML, but to provide a feasible option other than XML. Since Spring was released, the Spring development team has been constantly simplifying XML configuration, making the XML configuration method very mature. In addition, Spring 2.0 has provided a series of namespaces, this makes the XML configuration method a simple and powerful Bean definition method. In addition, some advanced functions of XML configuration are not directly supported by related annotations. Therefore, in most current projects, Bean configuration is either performed using pure XML configuration methods, or Bean configuration using annotation-based and XML-supplemented configuration methods.

There are three main reasons for the coexistence of the two: First, most of the projects developed using Spring are mostly based on XML configuration, spring must ensure that the annotation can coexist harmoniously with XML while introducing annotations. This is the premise. Second, because the annotation is introduced late, the function has not been developed for many years. Therefore, for complex configurations, annotations are still difficult to stand alone. In a period of time, XML is still needed to solve the problem. In addition, the Spring Bean configuration method is decoupled from the Spring core module. Therefore, changing the configuration method is transparent to the Spring framework itself. Spring can easily add annotation support by using BeanPostProcessor. This is very easy to implement technically.

To use the hybrid configuration method, you must first determine which configuration method is used. Different answers to this question will directly affect the implementation method. However, you don't have to worry about it, because the configuration method is simple and easy to understand whether it is mainly XML or annotation. There is no wrong decision here, because only the performance is different. First, let's assume that the XML configuration is the most important.

For large projects that already exist, Bean configuration may be performed in XML at the beginning, and annotation support will be added gradually in the future, in this case, you only need to define the class marked by @ Configuration as normal in the XML Configuration file, and register the Bean post-processor that processes the annotation. Example:

// Assume the following @ Configuration class exists:

Package bookstore. config;

Import bookstore. dao .*;

@ Configuration

Public class MyConfig {

@ Bean

Public UserDao userDao (){

Return new UserDaoImpl ();

}

}

In this case, you only need to make the following declaration in XML:

  

......

  

  

  

Because the Bean post-processor for annotation is enabled, when ApplicationContext is parsed to the MyConfig class, it will find that the class is labeled with the @ Configuration annotation, and then the @ Bean annotation method in the class will be processed, register the return values of these methods as the total Bean of the container.

For the above method, if there are multiple classes labeled @ Configuration, You need to list them one by one in the XML file. Another method is to use the automatic scanning function mentioned above. The configuration is as follows:

  

In this way, Spring will scan all the demos. the config package and its sub-packages identify all classes marked with @ Component, @ Controller, @ Service, and @ Repository annotations. Because the @ Configuration annotation itself is also marked with @ Component, spring will be able to identify the @ Configuration annotation class and parse it correctly.

For annotation-centered configuration, you only need to use the @ ImportResource annotation to introduce the existing XML, as shown below:

@ Configuration

@ ImportResource ("classpath:/bookstore/config/spring-beans.xml ")

Public class MyConfig {

......

}

// The initialization process of the container is consistent with the configuration-centric method:

AnnotationConfigApplicationContext ctx =

New AnnotationConfigApplicationContext (MyConfig. class );

......


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.