Spring Annotation Injection:<context:component-scan> detailed

Source: Internet
Author: User

Spring supports annotation injection from version 2.5, and annotation injection can save a lot of XML configuration work. Because annotations are written in Java code, annotation injection loses some flexibility, and we choose whether to enable annotation injection as needed.

We first look at a practical example of annotation injection, and then describe the use of context:component-scan in detail.

If you are already using Spring MVC annotation configuration, then you must already be injecting with annotations, this article does not involve spring MVC, and we use a simple example to illustrate the problem.

In this example we will define the following classes:

    1. Personservice class to provide person-related operations to the upper layer
    2. Persondao class, providing the DAO method to the Personservice class
    3. The person class, which defines the person-related attribute, is a Pojo
    4. App class, entry class, calling annotation injection Personservice class

The Personservice class is implemented as follows:

Package Cn.outofmemory.spring;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.Service; @Servicepublic class Personservice {@Autowiredprivate Persondao Persondao; Public person Getperson (int id) {return Persondao.selectpersonbyid (ID);}}

The @service annotation adornment is used on the service class and has a @autowired annotation decoration on its private field Persondao. @Service tell the spring container that this is a service class that will automatically load it into the spring container by default . The @Autowired annotation tells Spring that this field needs to be injected automatically .

Persondao class:

Package Cn.outofmemory.spring;import Org.springframework.context.annotation.scope;import org.springframework.stereotype.Repository; @Scope ("Singleton") @Repositorypublic class Persondao {public person Selectpersonbyid (int id) {Person p = new person ();p. SetId (ID);p. setName ("person name"); return p;}}

There are two annotations on the Persondao class, @scope and @repository, which specify that the scope of this spring Bean is a singleton, and you can designate the bean as prototype as needed,@ Repository note Specifies that this class is a container class and is an implementation of the DA layer class . This class we simply define a Selectpersonbyid method, the implementation of the method is also a false implementation, just declare a new instance of the person, and then set the property, return to him, in the actual application of the DA layer of the class must be from the database or other storage to fetch data.

Person class:

Package Cn.outofmemory.spring;public class Person {private int id;private String name;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}}

The person class is a pojo.

App class:

Package Cn.outofmemory.spring;import Org.springframework.context.applicationcontext;import org.springframework.context.support.classpathxmlapplicationcontext;/** * Hello spring! From outofmemory.cn * */public class App {public static void main (string[] args) {ApplicationContext AppC        Ontext = new Classpathxmlapplicationcontext ("/spring.xml");        Personservice service = Appcontext.getbean (Personservice.class);        Person p = Service.getperson (1);    System.out.println (P.getname ()); }}

In the main method of the app class, we initialized the ApplicationContext, then we get the Personservice class from which we annotated the annotation, then call the Getperson method of the object and output the Name property that returns the result.

annotation injection must also be in spring's configuration file To do the configuration, let's look at the contents of the Spring.xml file:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"        xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"        xmlns:context= " Http://www.springframework.org/schema/context "       xsi:schemalocation="/http www.springframework.org/schema/beans           http://www.springframework.org/schema/ beans/spring-beans.xsd           http://www.springframework.org/schema/context           http://www.springframework.org/schema/context/spring-context-3.0.xsd ">< Context:component-scan base-package= "cn.outofmemory.spring" use-default-filters= "false" ><context: Include-filter type= "regex" expression= "cn\.outofmemory\.spring\. [^.] + (dao| Service) "/> </context:component-scan></beans>
The XML namespace must be declared Xmlns:context in this configuration file, and the schema needs to be specified in the schemalocation:
Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0. Xsd

In this file, there is only one Context:component-scan node under the Beans root node, and this node has two properties Base-package property tells spring to scan the package, use-default-filters= "false" Indicates that you do not use the default filter, where the default filter scans the class containing the Service,component,repository,controller annotation adornments, and here we are at the end of the example, Deliberately set the Use-default-filters property to False.

The Context:component-scan node allows two sub-nodes <context:include-filter> and <context:exclude-filter>. The type and expression of the filter tag are described below:

Filter Type Examples Expression Description
Annotation Org.example.SomeAnnotation Target class conforming to Someannoation
Assignable Org.example.SomeClass Specify the full name of class or interface
Aspectj Org.example. *service+ AspectJ Language method
Regex Org\.example\. default.* Regelar Expression
Custom Org.example.MyTypeFilter Spring3 new custom type, actually org.springframework.core.type.TypeFilter

In our example, the type of filter is set to a regular expression, regex, in the regular. Represents all characters, while \. is the true. Character. Our regular represents a class that ends with a DAO or service.

We can also use annotaion to qualify, as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"        xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"        xmlns:context= " Http://www.springframework.org/schema/context "       xsi:schemalocation="/http www.springframework.org/schema/beans           http://www.springframework.org/schema/ beans/spring-beans.xsd           http://www.springframework.org/schema/context           http://www.springframework.org/schema/context/spring-context-3.0.xsd ">< Context:component-scan base-package= "cn.outofmemory.spring" use-default-filters= "false" ><context: Include-filter type= "Annotation" expression= "Org.springframework.stereotype.Repository"/> <context: Include-filter type= "Annotation" expression= "Org.springframework.stereotype.Service"/>  </context: component-Scan></beans> 

The type of Include-filter we specify here is Annotation,expression, which is the full name of the annotation class.

Another Context:conponent-scan node <context:exclude-filter> can be used to specify which classes to exclude, with the same usage as include-filter.

Finally we have to look at the results of the output, run the App class, output:

2014-5-18 21:14:18 org.springframework.context.support.AbstractApplicationContext Preparerefresh info: Refreshing org[ email protected]1cac6db:startup Date [Sun May 21:14:18 CST 2014]; Root of context hierarchy2014-5-18 21:14:18 Org.springframework.beans.factory.xml.XmlBeanDefinitionReader Loadbeandefinitions info: Loading XML Bean Definitions from class path resource [spring.xml]2014-5-18 21:14:18 Org.springfra Mework.beans.factory.support.DefaultListableBeanFactory preinstantiatesingletons Info: pre-instantiating singletons In Org.s[email protected]1fcf790:defining beans [Persondao,personservice, Org.springframework.context.annotation.internalConfigurationAnnotationProcessor, Org.springframework.context.annotation.internalAutowiredAnnotationProcessor, Org.springframework.context.annotation.internalRequiredAnnotationProcessor, Org.springframework.context.annotation.internalCommonAnnotationProcessor]; Root of Factory Hierarchyperson name

The first few lines are some debugging information for the spring output, and the last line is the output of our own program.








Spring Annotation Injection:<context:component-scan> detailed

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.