Prerequisites for 0 XML configuration with spring Annotations automated assembly and automatic scanning mechanism

Source: Internet
Author: User
Tags aop regular expression xmlns java se

First, learn about the new features added from spring2.5:

These new features include annotation-driven dependency injection (Annotation-driven Dependency injection), which automatically detects spring components on classpath using annotations instead of XML metadata, and annotations support for life-cycle methods, A new web controller model maps requests to annotated methods, supports new additions to the Junit4,spring XML namespace in the test framework, and so on.

1. Prerequisites introduce context to the schema namespace to add Context:annotation-config tags to the configuration file

In order to obtain new features, the new context schema namespace is introduced first, which provides a convenient configuration for annotation drivers, attribute file introduction, load-time weaving, and so on. We know that the annotation itself will not do anything, it only provides meta-data information. For the metadata information to really work, you must let the processor responsible for processing the metadata work.

<beans xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"
xmlns:tx= "Http://www.springframework.org/schema/tx"
Xmlns:jdbc= "Http://www.springframework.org/schema/jdbc"
xmlns:context= "Http://www.springframework.org/schema/context"
Xsi:schemalocation= "
Http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd
Http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd
Http://www.springframework.org/schema/jdbchttp://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
Http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsd
Http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

<!--

This configuration implicitly registers a number of processors to parse the annotation, the code can be directly used @autowired, @Required and so on annotaion.

Autowiredannotationbeanpostprocessor corresponds to @autowire,commonannotationbeanpostprocessor corresponding to @resource, etc., Persistenceannotationbeanpostprocessor,requiredannotationbeanpostprocessor Correspondence @required

-

<context:annotation-config/>

</beans>

2. Automatically assemble attribute instances.

to assemble using @autowired or @resource annotations, the differences between the two annotations are:

@Autowired is assembled by type by default , @Resource is assembled by name by default , and the bean that matches the name is not found to be assembled by type.

It is strongly recommended to discard @autowire using @resource reason Spring supports standard spring support JSR-250 annotations

In Java EE5, "Public annotations of the Java platform (Common Annotations for the Java Platform)" are introduced, and the public annotations are included from Java SE 61.

In version 2.5, the core (core) of the spring framework now supports the following JSR-250 annotations: @Resource @PostConstruct @PreDestroy

In conjunction with spring, these annotations can be used in any development environment-whether it's an application server or even an integrated test environment.

How to use: can be used to label a field or property on the setter method. if the label is on a field, you can omit the getter and setter methods for that property.

While

The name of the instance bean to be injected can be specified by the Name property of the @resource, if no Name attribute is specified,

1. When annotations are marked on a field, that is, the name of the default Fetch field is used as the bean name to find dependent objects

2. When annotations are labeled on the setter method of the property, the default property name is used as the bean name for the dependent object.

Used on fields

@Resource (name= "Persondao")

Private Persondaopersondao;

On the set method for the property

@Resource (name= "Persondao")

public void Setpersondao (Persondao Persondao) {

This.persondao = Persondao;

}

Note: If you do not specify a Name property, and the dependent object is not found by default name, @Resource annotation is rolled back to assembly by type. However, once the name attribute is specified, it can only be assembled by name.

3.spring Automatic scanning mechanism

spring2.5 introduced the component automatic scanning mechanism, which can look for classes labeled @component, @Service, @Controller, @Repository annotations under the classpath path. And to incorporate these classes into the spring container management. Its role is the same as using the Bean node configuration component in the XML file.

That is, the spring automatic scanning mechanism only looks for classes that contain @Component, @Service, @Controller, @Repository four annotations under the specified classpath.

To use the automatic scanning mechanism, we need to open the following configuration information:

1. The introduction of the context namespace requires the following information to be configured in the XML configuration file: First, the context namespace is introduced, and

2. Add Context:component-scan tags to the configuration file

<context:component-scan base-package= "*"/>

Where Base-package is the package (with child packages) that needs to be scanned.

Note:

1. When scanning elements using components , Autowiredannotationbeanpostprocessor and commonannotationbeanpostprocessor are implicitly included. That is, even a component will be automatically detected and woven-all without having to provide any bean configuration metadata in the XML. That is, if you use the Context:component-scan tag, you do not need to introduce the context:annotation-config tag

<context:component-scan/> also allows defining filters to include or exclude certain classes under the base package. Spring supports the following 4 types of filtering methods:

Filter Type Expression Example description
Annotation Org.example.SomeAnnotation filter out all classes that use someannotation annotations
Class name Specifies Org.example.SomeClass filter the specified class
Regular expression com\.kedacom\.spring\.annotation\.web\: * Filter Some classes with regular expressions
AspectJ expression org.example: *service+ filtering some classes by ASPECTJ expressions

In the case of regular expressions, I will cite an example of an application:

Java code
<context:component-scan base-package= "Com.casheen.spring.annotation" >
<context:exclude-filter type= "regex" expression= "com\.casheen\.spring\.annotation\.web\. * "/>
</context:component-scan>

<context:component-scan base-package= "Com.casheen.spring.annotation" >
<context:exclude-filter type= "regex" expression= "com\.casheen\.spring\.annotation\.web\. * "/>
</context:component-scan>

It is important to note that the <context:component-scan/> configuration item not only enables the ability to scan the class package to implement the annotation-driven bean definition. Note-driven auto-injection is also enabled (i.e., autowiredannotationbeanpostprocessor and commonannotationbeanpostprocessor are also implicitly registered internally), so when using < After Context:component-scan/>, you can remove the <context:annotation-config/>.

2. To add the appropriate annotations for the classes that need to be scanned, there are several types of annotations:

@Service for labeling business layer components,

@Controller is used to label control-layer components, such as action in struts,

@Repository is used to label data access Components, or DAO components.

And @component refers to the component, we can use this annotation to annotate when the component is not well categorized. These four kinds of annotations are only different in character, but they are the same in nature.

Summary of Details:

1. When we are testing, we use the Getbean () method of the ApplicationContext object to find the component. In the previous configuration file we will use the id attribute of the <bean> tag to define how to get the ID of the build after using automatic scan annotations.

In this case, spring will be annotated with the class name, and then the first letter of the class name into lowercase, put into the Getbean () method. such as: Userbizimpl class of the component ID will be Userbizimpl, when obtained is Context.getbean ("Userbizimpl");

So, we can customize the ID of the component when we use annotations.

of course you can. We need to add a custom class name after the annotation when adding annotations to the corresponding class, for example:

@Service ("userbiz")

public class Userbizimpl implements Userbiz {

......

}

When we acquire the component, it is Context.getbean ("userbiz");

2. In the configuration file we can set the scope scope of the component (bean), its default value is a singleton mode, then in the case of adding annotations, how do we set the scope range of the component?

We can use another annotation @scope ("prototype") to set it directly while adding annotations to the class, as follows

@Service ("Userbiz") @Scope ("prototype")

public class Userbizimpl implements Userbiz {

......

}

3. When using annotations, set the initialization and destruction methods for the components:

In the appropriate class for adding annotations, if you want to initialize or destroy a method, we can add annotations directly to the method, as follows:

@PostConstruct

public void AddItem () {

SYSTEM.OUT.PRINTLN ("initialization method");

}

@PreDestroy

public void TestItem () {

System.out.println ("Releasing resources");

}

4. How to perform dependency injection after using spring to automatically scan components.

Use annotations @resource and @autowired, and set names for dependent objects, for example:

@Resource (name= "Userdao")

Private Userdao Userdao = null;

First it will look for the component (bean) that spring automatically scans and joins to the spring container according to its name, and if it has the same name, it does the dependency injection if it does not have the same name. Components are found based on the type area.

Once you understand the above, you can easily implement the SPIRNG 0 configuration.

------------------------------------------------------------------------------------------------

Project post-development work defines a large number of beans and now requires logging for each database operation, so a logbiz is defined,

If you follow the usual practice of modifying all of the configuration files to add property attributes, use the auto-injection mechanism now.

Add a common log method in Baseaction, set aside a iogbiz interface, and in the inherited subclass action, define a Logbiz property and use @resouce annotations. Can.

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.