1. identify the class as a Bean using @Repository, @Service, @Controller, and @Component:
Spring has been introduced since version 2.0 to simplify the development of spring. @Repository annotations are among the first to be introduced to identify the classes of the data Access layer (DAO layer) as Spring beans. Simply label the annotation on the DAO class. Also, in order for Spring to be able to scan classes in Classpath and identify @Repository annotations, you need to enable the automatic scanning of beans in the XML configuration file, which can be achieved by <context:component-scan/>. As shown below:
First, use @Repository to declare a DAO class as a Bean:
First use @Repository to declare the DAO class as Bean package Bookstore.dao; @Repository public class Userdaoimpl implements userdao{...}//second, start Spring's Auto Scan feature in an XML configuration file <beans ... > ... <c Ontext:component-scan base-package= "Bookstore.dao"/> ... </beans>
Second, start Spring's automatic scanning in an XML configuration file:
<beans ... > ... <context:component-scan base-package= "Bookstore.dao"/> ... </beans>--
In this way, we no longer need to explicitly use <bean/> for bean configuration in XML. Spring automatically scans for all class files under the specified package and its base-package when the container is initialized, and all classes that are annotated @Repository are registered as spring beans.
Why @Repository can only be labeled on DAO classes. This is because the annotation does not simply recognize the class as a Bean, but it also encapsulates the data access exception that is thrown in the annotated class as the data access exception type for Spring. Spring itself provides a rich and independent data access exception structure that encapsulates the exceptions thrown by different persistence layer frameworks, leaving the exception to the underlying framework.
The 2.Spring 2.5 adds additional three annotations with similar functionality on a @Repository basis:
@Component, @Service, @Constroller, which are used in different levels of software systems:
@Component is a generalization concept that simply represents a component (Bean) that can function at any level. @Service usually works in the business layer, but this feature is the same as @Component. @Constroller usually works on the control layer, but this function is the same as @Component.
By using @Repository, @Component, @Service, and @Constroller annotations on a class, Spring automatically creates the appropriate Beandefinition object and registers it with the ApplicationContext. These classes become Spring-managed components. These three annotations are used in exactly the same way as @Repository, except for classes that function at different levels of software.
In addition, in addition to the four annotations above, a user can create a custom annotation and then annotate @Component on the annotation, so that the custom annotation has the same functionality as the @Component. However, this function is not commonly used.
3.Spring mechanism for using annotations:
When a bean is automatically detected, its bean name is generated based on the Beannamegenerator policy of that scanner. By default, name is taken as the Bean's name for @Component, @Repository, @Service, and @Controller that contain the Name property. If this annotation does not contain a name value or a component that is found by a custom filter, the default Bean name is the unqualified class name that begins with lowercase. If you do not want to use the default bean naming policy, you can provide a custom named policy. The Beannamegenerator interface is implemented first, confirming that a default parameterless construction method is included. It then provides a fully qualified class name when the scanner is configured, as follows:
<beans ...> <context:component-scan base-package= "a.b" name-generator= "A.simplenamegenerator"/> </ Beans>
Like a spring bean configured through XML, the default scope of the bean, identified by the note above, is "Singleton," which, in conjunction with the four annotations, can specify the scope of the bean while the bean is being annotated, Spring 2.5 introduces @Scope annotations 。 You can use this annotation by providing only the name of the scope, as follows:
@Scope ("prototype") @Repository public class Demo {...}
If you want to provide a custom scope resolution policy without using a method based on annotations, simply implement the Scopemetadataresolver interface and confirm that there is a default constructor method with no parameters. The fully qualified class name is then provided when the scanner is configured:
<context:component-scan base-package= "a.b" scope-resolver= "Footmark". Simplescoperesolver "/>
4. use @PostConstruct and @PreDestroy Specify lifecycle callback methods:
Spring beans are managed by the Spring IoC container, initialized and destroyed by the container (the prototype type is not managed by the container after the container is initialized), and normally we do not need to focus on the container's initialization and destruction operations on the Bean. A Bean created by a constructor or factory method is already initialized and immediately available. In some cases, however, it may be necessary for us to do some additional initialization or destruction operations, usually for some resource acquisition and release operations. Spring 1.x provides two ways for users to specify how to perform a lifecycle callback.
The first way:
Is the two interfaces that Spring provides: Initializingbean and Disposablebean. If you want to perform some custom actions after the bean initialization completes, you can have the bean implement the Initializingbean interface, which contains a afterpropertiesset () method that is automatically invoked after the container has set properties for the bean If the bean implements the Disposablebean interface, the container will invoke the Destroy () method of the interface before destroying the bean. The disadvantage of this approach is that it is not recommended to have the Bean class implement the interface provided by spring, increasing the coupling between the code and the Spring framework.
The second way is:
Use the <bean> Init-method and Destroy-method properties in an XML file to specify the callback method after initialization and before destruction, and the code does not need to implement any interfaces. The values of these two properties are the initialization and destruction methods in the corresponding Bean class, the method name is arbitrary, but the method cannot have parameters. Examples are as follows:
<bean id= "UserService" class= "Bookstore.service.UserService" init-method= "Init" destroy-method= "destroy" > ... </bean>
The Third Way:
Spring 2.5 provides support for JSR-250 on the basis of retaining both of these approaches. The JSR-250 specification defines two annotations for specifying a declaration cycle method: @PostConstruct and @PreDestroy. These two annotations are very simple to use, simply by marking them with the callback method that was executed after initialization or by the callback method that was executed before it was destroyed. Because annotations are used, the appropriate Bean post processor needs to be configured, that is, add the following line to the XML:
<context:annotation-config/>
The first of these three ways of specifying life cycle callback methods is not recommended, not as flexible as in the latter two ways, and virtually increases the coupling of the code to the framework. The next two ways developers can choose one of them according to their habits, but it's best not to mix them up to avoid increasing maintenance.
5. use @Required for Bean dependency checking:
The role of dependency checking is to determine whether the corresponding Setter method for a given Bean is invoked at the time of instantiation. Instead of determining if the field already has a value. When Spring makes dependency checking, it only determines whether the attribute uses Setter injection. If a property does not use Setter injection, even if a value has been injected into the property through the constructor, Spring still thinks it does not perform the injection and throws an exception. In addition, Spring does not have any requirements for the injected value, even though the injected <null/>,spring is considered to perform a dependency injection, regardless of whether the injection is performed through a Setter.
The <bean> tab provides a Dependency-check property for dependency checking. The value of this property includes the following: None-the default does not perform dependency checking. You can use the Default-dependency-check property on the <beans> tab to change the default value. Simple-Checks the original base type and collection type. Objects--Checks for complex types (except for types that are checked by simple). All-check all types.
Older versions are set in the configuration file using Dependency-check, with the disadvantage of coarse granularity. Use the @Required annotations provided by Spring2.0 to provide finer granularity of control. @Required annotations can only be annotated on top of the Setter method. Because the essence of dependency injection is to check whether the Setter method is invoked, instead of actually checking whether the property is assigned and what values are assigned. If the annotation is annotated in a setxxxx ()-type method, it is ignored.
In order for Spring to be able to process the annotation, the appropriate Bean post processor needs to be activated. To activate the Post processor, simply add the following line to the XML:
<context:annotation-config/>
When a Setter method that is labeled @Required is not invoked, Spring throws an exception when parsing to remind the developer to set the corresponding attribute.
6. use @Resource, @Autowired, and @Qualifier to specify the automatic assembly policy for the Bean:
Automatic assembly means that Spring, when assembling a bean, injects a bean that needs a reference type from a bean, based on the specified automatic assembly rules. The <bean> element provides a Autowire property that specifies the automatic assembly type, which has the following options: No--explicitly specifies that automatic assembly is not used. ByName--If there is a bean that is consistent with the name of the current property, it is injected using the bean. If the name matches but the type does not match, an exception is thrown. If there is no matching type, then nothing is done. Bytype--If there is a bean (of the same type or subtype) that is consistent with the current property type, it is injected using the bean. Bytype is able to identify the factory method, that is, to identify the return type of Factory-method. Throws an exception if there are multiple type-consistent beans. If there is no matching type, then nothing is done. constructor-similar to Bytype, except that it is for constructor injection. Throws an exception if there is no current Bean that matches the constructor's parameter type. When using this assembly mode, the constructor with the most parameters is preferred. AutoDetect--depending on the Bean's introspection mechanism, it is decided to use Bytype or constructor for automatic assembly. If the Bean provides a default constructor, the Bytype is used, otherwise the constructor is used for automatic assembly.
When using Bytype or constructor type automatic assembly, automatic assembly also supports an array of reference types or uses a generic collection, so that Spring examines all the types of beans in the container that match, makes up the collection or array, and then executes the injection. For a MAP type that uses generics, if the key is a String type, Spring will also automate the assembly, with all types matching the bean as the value and the bean's name as the key.
We can add the Default-autowire property to <beans> and set the default automatic encapsulation policy. The default value is "no". If you also specify a property or Constructor-arg label when you use automatic assembly, the explicitly specified value overrides the automatically assembled value. The current automatic encapsulation does not support simple types, such as base types, String, Class, and their array types.
When matching by type (possibly Bytype, constructor, AutoDetect), there may be multiple beans for the same type, and if the injected property is an array, collection, or MAP, this may not be a problem, but if it is simply a reference type, an exception is thrown. There are several solutions to this problem: canceling the Bean's automatic assembly feature and using an explicit injection. We may not want a bean to be a candidate for automatic encapsulation as another bean, and we can add autowire-candidate= "false" to the <bean>. (The Autowire-candidate property and the Autowire attribute are independent and irrelevant to each other.) A Bean can set Autowire-candidate to false and use the Autowire attribute. In addition, we can set the <beans> Default-autowire-candidates property, where you can specify the matching pattern that can be used to assemble the candidate Bean automatically, such as Default-autowire-candidates= "*serv,*dao", which means that all names with Serv or DAO end of the bean are listed as candidates, others are ignored, equivalent to other beans are designated as autowire-candidate= " False, you can explicitly specify autowire-candidate= "true" for <bean> at this time. The settings specified on <bean> are to overwrite the settings specified on <beans>. If you have preferred beans in multiple beans of the same type, you can set the <bean> primary property to "true" so that the bean is used as a priority when assembling automatically. Autowire-candidate cannot be set to false at this time. If you are using more than Java version 5, you can use annotations for finer granularity of control.
7. Perform automatic assembly using @Autowired and @Qualifier annotations:
Assembly using @Autowired annotations, which can only be matched according to type. @Autowired annotations can be used for Setter methods, constructors, fields, and even common methods, provided that the method must have at least one parameter. @Autowired can be used for arrays and collection types that use generics. Spring then injects all the type-compliant beans in the container. If the key of the map is of type String when the @Autowired callout is acting on the map type, Spring adds the bean of all types in the container corresponding to the value of map, using the bean's ID or name as the The key of the MAP.
When a @Autowired annotation is applied to a normal method, a side effect is that the method is called when the container initializes the Bean instance. Of course, the premise is that automatic assembly is performed, and the method is not executed for situations that do not meet the assembly conditions.
When the @Autowired is annotated, an automatic injection is not satisfied, and an exception is thrown. We can add a Required=false attribute to the @Autowired annotation to change this behavior. In addition, there can be only one constructor in each class @Autowired. Required () property is true. Otherwise, there will be a problem. If more than one constructor is annotated with a @Autowired, Spring will use the greedy algorithm to match the constructor (the longest constructor).
@Autowired also has an effect, if you label it in beanfactory type, ApplicationContext type, Resourceloader type, applicationeventpublisher type, Messagesource type, then Spring automatically injects instances of these implementation classes without additional action.
When the type of multiple beans in the container is the same as what needs to be injected, the injection will not execute, and we can add a candidate value to the @Autowired by adding a @Qualifier callout after the @Autowired, providing a String value as the candidate an name. Examples are as follows:
@Autowired (Required=false) @Qualifier ("PPP") public void Setperson (person p) {}
@Qualifier can even be used as a parameter to a method (for a method with only one argument, we can place @Qualifer callout above the method declaration, but it is recommended to precede the argument), for example:
@Autowired (required=false) public void SayHello (@Qualifier ("PPP") person p,string name) {}
We can specify the qualifier name of a Bean in the configuration file as follows:
<bean id= "Person" class= "Footmark.spring.Person" > <qualifier value= "PPP"/> </bean>
If you do not explicitly specify the qualifier name of the bean, the default name is the name of the bean. Typically, qualifier should have business implications, such as "domain", "persistent", and so on, rather than "person".
We can also label the @Qualifier on the collection type, so all the Qualifier names are injected into the same Bean with the specified value.
Finally, you need to specify the property values for each custom annotation in the configuration file. We can use <meta> tags to replace <qualifier/> tags, if <meta> tags and <qualifier/> tags appear at the same time, then the first use of the <qualifier> Label. If there is no <qualifier> tag, the <qualifier> tag is encapsulated with a key value pair provided by <meta>. Examples are as follows:
<bean class= "Footmark. HelloWorld "> <qualifier type=" moviequalifier "> <attribute key=" format "value=" VHS "/> <attribute key = "Genre" value= comedy "/> </qualifier> </bean> <bean class=" Footmark. HelloWorld "> <meta key=" format "value=" DVD "/>" <meta key= "Genre" value= "Action"/> </bean>
The post processing registration for @Autowired annotations is similar to the previous one by adding the following line to the configuration file:
<context:annotation-config/>
If @Autowired inject a system type such as Beanfactory, ApplicationContext, Resourceloader, then you do not need to @Qualifier, and will be ignored even if @Qualifier annotations are provided. , and for automatic assembly of custom types, automatic assembly matching fails if @Qualifier annotations are used and there is no name matching the Bean.
8. use @resource and @Qualifier annotations:
If you want to perform automatic assembly by name, you should use the @Resource annotations provided by JSR-250 instead of using a combination of @Autowired and @Qualifier.
@Resource perform automatic encapsulation using the ByName method. @Resource annotations can be used for Setter methods, fields with one parameter, and for common methods with one parameter. @Resource Note has a Name property that specifies the name of the Bean in the configuration file. If the Name property is not specified, the default value is the name of the field or property. @Resource and @Qualifier are still valid, but @Qualifier is almost equivalent to the Name property for @Resource.
If the @Resource does not specify the Name property, then the ByName match fails with the Bytype to continue the match, and if it fails again, an exception is thrown. If the name attribute is not explicitly specified for @Resource annotation, if it is annotated in the Beanfactory type, ApplicationContext type, Resourceloader type, Applicationeventpublisher type, Messagesource type, then Spring automatically injects instances of these implementation classes without additional action. The Name property does not need to be specified (or specified as ""), or the injection fails, and if @Qualifier is used, the annotation is ignored. For injection of user-defined types, @Qualifier and name are equivalent and are not ignored.
The primary and Autowire-candidate properties of <bean> are still valid for @Resource, @Autowired.
9. use @Configuration and @Bean to make a statement of the Bean:
Although Spring has provided more than 10 annotations since release 2.0, these annotations are provided only to simplify the configuration of XML in some cases and not to replace the XML configuration method. This can be seen from the initialization classes of the Spring IoC container: The most common implementation classes for APPLICATIONCONTEXT interfaces are Classpathxmlapplicationcontext and Filesystemxmlapplicationcontext, as well as Portlet-oriented xmlportletapplicationcontext and web-oriented xmlwebapplicationcontext, are all oriented to of XML. Spring 3.0 adds two additional implementation classes: Annotationconfigapplicationcontext and Annotationconfigwebapplicationcontext. As can be seen from the name, they are born for annotations, directly dependent on annotations as the container configuration information source of the IoC container initialization class. Since Annotationconfigwebapplicationcontext is a annotationconfigapplicationcontext version of the Web, its usage is little different than the latter, so this article will Annotationconfigapplicationcontext as an example to explain.
Annotationconfigapplicationcontext with @Configuration and @Bean annotations, XML configuration is no longer the only way to configure the Spring IoC container. There is a competitive relationship between the two, but in most cases it is a collaborative relationship, and the combination of the two makes the Spring IoC container configuration simpler and more powerful.
Before, we focused the configuration information in XML and now use annotations, and the carrier of configuration information is transferred from XML files to Java classes. We usually end the class name of the class used to store the configuration information with "Config", such as Appdaoconfig.java, Appserviceconfig.java, and so on. We need to add @Configuration annotations to the class that specifies the configuration information to make it clear that the class is the information source for the Bean configuration. And Spring has the following requirements for annotations Configuration classes: The configuration class cannot be final; the configuration class cannot be localized, that is, the configuration class cannot be defined within the methods of other classes; The configuration class must have an parameterless constructor.
Annotationconfigapplicationcontext recognizes the return value of the method that is @Bean in the configuration class as a Spring Bean and registers it in the container, managed by the IoC container. The role of @Bean is equivalent to the <bean/> label in the XML configuration. Examples are as follows:
@Configuration public class bookstoredaoconfig{@Bean public Userdao Userdao () {return new Userdaoimpl ();} @Bean public Bo Okdao Bookdao () {return new Bookdaoimpl ();}}
When Spring resolves to the above file, it recognizes all the methods that are annotated @Bean, executes it, and registers the return value of the method (here Userdaoimpl and Bookdaoimpl objects) into the IoC container. By default, the Bean's name is the method name. Therefore, the XML configuration equivalent to the above configuration is as follows:
<bean id= "Userdao" class= "Bookstore.dao.UserDaoImpl"/> <bean id= "Bookdao" class= "Bookstore.dao.BookDaoImpl" "/>
@Bean has the following four properties: Name--Specifies the name of one or more beans. This is equivalent to the Name property of <bean> in the XML configuration. Initmethod-the container will invoke the method specified by the property after the Bean has been initialized. This is equivalent to the Init-method property of <bean> in the XML configuration. Destroymethod-this property is similar to the Initmethod feature, which calls the method specified by the container before it destroys the Bean. This is equivalent to the Destroy-method property of <bean> in the XML configuration. Autowire-Specifies the automatic assembly policy for the Bean property, which is a three static property of the Autowire type. Autowire.by_name,autowire.by_type,autowire.no. There is less constructor than the value of the Autowire attribute in the XML configuration, because constructor is meaningless here.
@Bean does not directly provide properties for the specified scope, it can be implemented by @Scope, and the use of @Scope is listed above.
The following explains the annotation based container initialization. Annotationconfigapplicationcontext provides three constructors for initializing a container. Annotationconfigapplicationcontext (): The constructor initializes an empty container that does not contain any Bean information, needs to register the configuration class later by calling its register () method, and invokes the refresh () method to refresh the container. Annotationconfigapplicationcontext (CLASS<?>. annotatedclasses): This is the most commonly used constructor, by passing the configuration class involved to the constructor, To implement the automatic registration of the beans in the corresponding configuration class into the container. Annotationconfigapplicationcontext (String ... basepackages): The constructor automatically scans for all the classes under the given package and its children, and automatically recognizes all the Spring beans and registers them in the container. It not only recognizes the annotation @Configuration configuration class and resolves it correctly, but also recognizes classes that use @Repository, @Service, @Controller, @Component annotations.
In addition to using the third type of constructor above to allow the container to automatically scan the Bean's configuration information, Annotationconfigapplicationcontext also provides a scan () method that is similar in functionality to the above, which is mainly used to dynamically increase after container initialization Bean to the container. After this method is invoked, it is often necessary to manually call refresh () to refresh the container immediately for the change to take effect immediately.
It should be noted that when parsing a configuration class, Annotationconfigapplicationcontext registers itself as a Bean for the configuration class, because it is @Component annotated when the @Configuration annotation itself is defined. So it can be said that a @Configuration is also a @Component. In most cases, the bean is not used by the developer, and ideally, the bean should be transparent to the developer. The definition of @Configuration is as follows:
@Target ({elementtype.type}) @Retention (retentionpolicy.runtime) @Documented @Component public @interface Configuration {String value () Default "";}
In a general project, for clarity, multiple XML configuration files are usually defined according to the module or structure of the software, and then a configuration file for the portal is defined, which uses <import/> to organize other configuration files. Finally, just pass the file to the Classpathxmlapplicationcontext constructor. For annotations based configurations, Spring also provides similar functionality by simply defining a Portal configuration class and using @Import annotations on that class to introduce additional configuration classes, and finally simply passing the entry class to the Annotationconfigapplicationcontext. The specific examples are as follows:
@Configuration @Import ({bookstoreserviceconfig.class,bookstoredaoconfig.class}) public class bookstoreconfig{...}
A mixed use of XML and annotations for Bean configuration:
Design @Configuration and @Bean are not intended to completely replace XML, but rather to have a viable alternative to XML. Since spring was released, the spring development team has been simplifying the XML configuration, making the XML configuration approach very mature, coupled with the support of a series of namespaces after Spring 2.0, making XML configuration A simple, powerful way to define beans 。 Also, some of the advanced features of XML configuration are currently not directly supported by annotations. Therefore, in most of the current projects, you either use a pure XML configuration to make the bean configuration, or you can configure the bean in a configuration way that is annotated primarily and XML is supplemented.
The reason for the coexistence of the two is mainly attributed to three reasons: first, most of the projects using Spring for development, almost all are based on XML configuration, spring in the introduction of annotations must ensure that annotations and XML coexist harmoniously, this is a prerequisite; Due to the late introduction of annotations, so the function has not developed for many years of XML strong, therefore, for complex configuration, annotations are still difficult to independently, in a period of time still need XML coordination to solve the problem. In addition, the spring Bean's configuration is decoupled from the Spring core module, so changing the configuration is transparent to the spring's framework itself. Spring can easily increase support for annotations by using the Bean Post processor (beanpostprocessor). This is a very easy thing to achieve in technology.
To use a mixed configuration approach, you first need to determine which configuration is the primary. The different answers to this question will directly affect the way in which they are implemented. However, there is no need to worry about this, because the configuration is simple and easy to understand, whether it is primarily XML or annotated. There is no wrong decision, because it is just a different way of behaving. Let's first assume that XML configuration is the primary case.
For large projects that already exist, it is possible to start with the Bean configuration in XML, followed by gradually adding annotation support, then we simply in the XML configuration file @Configuration annotated class defined as ordinary <bean>, while registering the processing of annotations The Bean can be followed by the processor. Examples are as follows:
Suppose there are @Configuration classes as follows: Package bookstore.config; Import bookstore.dao.*; @Configuration public class myconfig{@Bean public Userdao Userdao () {return new Userdaoimpl ();}}
At this point, just make the following declaration in the spring XML configuration file:
<beans ... > ...
<context:annotation-config/>
<bean class= "Demo.config.MyConfig"/>
Because the annotation-oriented Bean post processor is enabled, it is found that the class is annotated with @Configuration annotations when applicationcontext resolves to the Myconfig class.
The methods that are annotated @Bean in the class are then processed and the return values of these methods are registered as the total Bean of the container.
For the above approach, if there are multiple classes that have @Configuration annotated, you need to list them in the XML file. Another way is to use the automatic scanning feature mentioned earlier
, CONFIGURED as follows:
<context:component-scan base-package= "Bookstore.config"/>
This way, Spring scans all demo.config packages and the classes in their child packages, identifying all tags @Component, @Controller, @Service, @Repository
annotation classes, as @Configuration annotations themselves are @Component annotated, Spring will be able to recognize @Configuration annotation classes and parse them correctly.
For an annotation-centric configuration, just use @ImportResource annotations to introduce the presence of XML, as follows:
@Configuration @ImportResource ("Classpath:/bookstore/config/spring-beans.xml") public class myconfig{...}// The initialization process for a container is consistent with a purely configuration-centric approach: annotationconfigapplicationcontext CTX = new Annotationconfigapplicationcontext ( Myconfig.class); ......