Spring annotation injection: (context: component-scan)

Source: Internet
Author: User

Spring annotation injection: (context: component-scan)

Spring versions 2.5 support annotation injection, which saves a lot of xml configuration work. Because annotations are written into java code, annotation injection will lose some flexibility. We need to choose whether to enable annotation injection as needed.

First, let's take a look at the actual example of annotation injection, and then introduce the use of context: component-scan in detail.

If you are already using spring mvc annotation configuration, you must already be using annotation injection. This article will not involve spring mvc. We will use a simple example to illustrate the problem.

In this example, the following classes are defined:

  1. PersonService class, which provides Person-related operations to the upper layer
  2. The PersonDao class provides the DAO method for the PersonService class.
  3. Person class, which defines the Person-related attributes and is a POJO
  4. App class, entry class, call 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 is used in the Service class, And the @ Autowired annotation is used in its private field PersonDao. @ Service tells the spring container that this is a Service class and is automatically loaded to the spring container by default. The @ Autowired annotation tells spring that this field needs to be automatically injected.

    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. The former specifies that the scope of this spring bean is a singleton. You can also specify this bean as prototype as needed, @ Repository the annotation specifies that this class is a container class, which is the implementation of the DA layer class. This class simply defines a selectPersonById method. The implementation of this method is also a false implementation. It just declares a new Person instance, sets the attribute, and returns it, in actual applications, the DA-layer class must retrieve data from the database or other storage.

    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 Type:

    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 appContext = 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 initialize ApplicationContext, get the PersonService class we annotated and injected from it, call the getPerson method of this object, and output the name attribute of the returned result.

    Annotation injection must also be configured in the spring configuration file. Let's take a look at the content of the spring. xml file:

       
       
        
          
        
       
    The xml namespace xmlns: context must be declared in this configuration file, and schema must be specified in 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. This node has two attributes, the base-package attribute, that is, the package to be scanned by spring, use-default-filters = "false" indicates that the default filter is not used. The default filter here scans classes that contain Service, Component, Repository, and Controller annotations, in this example, we intentionally set the use-default-filters attribute to false.

    Context: component-scan nodes can have two subnodes And . The type and expression of the filter tag are described as follows:

    Filter Type Examples Expression Description
    Annotation Org. example. SomeAnnotation Target class conforming to SomeAnnoation
    Assignable Org. example. SomeClass Full name of the specified class or interface
    Aspectj Org. example... * Service + AspectJ Encryption Method
    Regex Org \. example \. Default .* Regelar Expression
    Custom Org. example. MyTypeFilter Spring3 adds a new self-defined Type to org. springframework. core. type. TypeFilter.

    In our example, we set the filter type to a regular expression, regex. Note that in the regular expression, all characters are represented, while \. Indicates true. characters. Our regular expression indicates the class ended with Dao or Service.

    We can also use annotaion to limit it, as shown below:

       
       
        
          
           
        
       

    Here, the type of the specified include-filter is annotation, and expression is the full name of the annotation class.

    In addition, context: conponent-scan nodes also have It can be used to specify the class to be excluded. The method is consistent with include-filter.

    Finally, let's look at the output result. Run the App class and output:

    21:14:18 org. springframework. context. support. abstractApplicationContext prepareRefresh information: Refreshing org. springframework. context. support. classPathXmlApplicationContext @ 1cac6db: startup date [Sun May 18 21:14:18 CST 2014]; root of context hierarchy2014-5-18 21:14:18 org. springframework. beans. factory. xml. xmlBeanDefinitionReader loadBeanDefinitions information: Loading XML bean definitions from class path resource [spring. xml] 21:14:18 org. springframework. beans. factory. support. defaultListableBeanFactory preInstantiateSingletons: Pre-instantiating singletons in org. springframework. beans. factory. support. defaultListableBeanFactory @ 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 output by spring, and the last line is the output of our own program.








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.