Energy project XML file tag interpretation--<context:component-scan>

Source: Internet
Author: User

    <Context:component-scanBase-package= "Com.xindatai.ibs"use-default-filters= "false">        <Context:include-filtertype= "Annotation"expression= "Org.springframework.stereotype.Controller" />        <Context:include-filtertype= "Annotation"expression= "Org.springframework.web.bind.annotation.ControllerAdvice"/>    </Context:component-scan>

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; @Service  public  class   Personservice {@Autowired  private   Persondao Persondao;  public  person Getperson (int   ID) { return   person    Dao.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" " @Repository  public  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 a 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:

 Packagecn.outofmemory.spring; Public classPerson {Private intID; PrivateString name;  Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }}

The person class is a pojo.

App class:

 Packagecn.outofmemory.spring;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;/*** Hello spring! from outofmemory.cn **/ Public classApp { Public Static voidMain (string[] args) {ApplicationContext appContext=NewClasspathxmlapplicationcontext ("/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.

Note Injection must also be configured in the spring configuration file, and we'll look at the contents of the Spring.xml file:

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "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-cont Ext-3.0.xsd ">    <Context:component-scanBase-package= "Cn.outofmemory.spring"use-default-filters= "false">        <Context:include-filtertype= "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"?><Beansxmlns= "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-cont Ext-3.0.xsd ">

<Context:component-scanBase-package= "Cn.outofmemory.spring"use-default-filters= "false"> <Context:include-filtertype= "Annotation"expression= "Org.springframework.stereotype.Repository"/> <Context:include-filtertype= "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:

 the-5- -  +: -: -Org.springframework.context.support.AbstractApplicationContext Preparerefresh Info: Refreshing org[email Protected]1cac6db:startupDate[Sun May -  +: -: -Cst the]; Root of context Hierarchy the-5- -  +: -: -Org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadbeandefinitions Info: Loading XML bean Definitions fromclasspath resource [Spring.xml] the-5- -  +: -: -org.springframework.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 hierarchy personname 

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

Energy project XML file tag interpretation--<context:component-scan>

Related Article

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.