Spring Basic Series 7-automatic scanning of components or beans

Source: Internet
Author: User

Spring Basic Series 7--auto scan component or Bean reprint: http://www.cnblogs.com/leiOOlei/p/3547589.html One, spring Auto scanning components--Auto Sweep      The description component 1.      Declares components manually--manual configuration component 2.      Auto Components scanning--Auto-scan component 3.      Custom Auto Scan component name--to customize the scan component name 4.      Auto Components Scan antotation types--Automatic Scan component annotation type two, Spring filter in Auto scanning--Filter component 1 in automatic scanning.      Filter Component--include 2. Filter Component--exclude

One, Spring Auto scanning components--Auto Scan component

Typically you can declare a bean or component in an XML configuration file, and then the spring container will check and register your bean or component. In fact, Spring supports automatic scanning of beans or component, and you can no longer have to make tedious claims in the XML file that bean,spring automatically scans, checks the bean or component of the package you specify.

Here's a simple spring Project that includes the customer, Service, and DAO layers, so let's look at the differences between manual and automated scans.

1. Declares components manually--manual configuration component

Let's look at the normal manual configuration of a bean

DAO layer, Customerdao.java as follows:

Package Com.lei.customer.dao; public class Customerdao {    @Override public    String toString () {        return ' Hello, this is Customerdao ";    }    }

Service layer, Customerservice.java as follows:

Package com.lei.customer.services; Import Com.lei.customer.dao.CustomerDAO; public class CustomerService {    Customerdao Customerdao;     public void Setcustomerdao (Customerdao customerdao) {        This.customerdao = Customerdao;    }     @Override public    String toString () {        return "customerservice [customerdao=" + Customerdao + "]";    }}

Configuration files, spring-customer.xml files are as follows:

<beans xmlns= "Http://www.springframework.org/schema/beans"    xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "    xsi:schemalocation=" Http://www.springframework.org/schema/beans/    http Www.springframework.org/schema/beans/spring-beans-2.5.xsd ">     <bean id=" customerservice "class=" Com.lei.customer.services.CustomerService ">        <property name=" Customerdao "ref=" Customerdao "/>    </bean>     <bean id= "Customerdao" class= "Com.lei.customer.dao.CustomerDAO"/> </beans>

Run the following code, App.java as follows:

Package Com.lei.common; Import Org.springframework.context.applicationcontext;import Org.springframework.context.support.ClassPathXmlApplicationContext; Import Com.lei.customer.services.CustomerService; public class App {public    static void Main (string[] args)    {        ApplicationContext context =           new CLASSPATHXM Lapplicationcontext (new string[] {"Spring-customer.xml"});         CustomerService cust = (customerservice) context.getbean ("CustomerService");        SYSTEM.OUT.PRINTLN (Cust);     }}

[Customerdao=hello, this is Customerdao]

2. Auto Components scanning--Automatic Scan component

Now, take a look at how to use spring's automatic scanning.

Use the annotation @component to indicate that this class is an auto-scan component.

Customer.java as follows:

Package Com.lei.customer.dao; Import org.springframework.stereotype.Component; @Componentpublic class Customerdao {    @Override public    String toString () {        return ' Hello, this is Customerdao ";    }    }

Customerservice.java as follows:

Package com.lei.customer.services; Import Org.springframework.beans.factory.annotation.autowired;import org.springframework.stereotype.Component; Import Com.lei.customer.dao.CustomerDAO; @Componentpublic class CustomerService {    @Autowired    Customerdao Customerdao;     @Override public    String toString () {        return "customerservice [customerdao=" + Customerdao + "]";    }}

The configuration file Spring-customer.xml is as follows

<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-2.5.xsd    http://www.springframework.org/schema/context    http://www.springframework.org/ Schema/context/spring-context-2.5.xsd ">     <context:component-scan base-package=" Com.lei.customer "/> </beans>

Attention:

In the XML file above, the "Context:component-scan" tab is added, which introduces the spring's automatic scanning feature, Base-package represents where your component is stored, Spring will scan the bean under the corresponding folder (annotated with @component) and register the beans in the container.

The result of the final run is consistent with the manual configuration.

3. Custom Auto Scan component name--customized scan component name

In the above example, by default, spring will turn the first letter of the component class into lowercase, as the name of the auto-scan component, such as "customerservice" into "customerservice", you can use "customerservice "This name calls the component, as follows:

CustomerService cust = (customerservice) context.getbean ("CustomerService");

You can create a custom component name like this:

@Service ("AAA") public class customerservice ...

Now, you can invoke your own defined component, as follows:

CustomerService cust = (customerservice) context.getbean ("AAA");

4. Auto Components scan antotation types--Auto scan component Annotation type

There are 4 types of annotations, namely:

@Component--Represents an automatic scan Component

@Repository--A DAO component that represents the persistence layer

@Service--service component representing the business logic layer

@Controller--Represents the Controller component of the layer

The above 4 kinds, in the application, we should use which kind? Let's take a look at the source code of @repository, @Service, @Controller

@Target ({elementtype.type}) @Retention (retentionpolicy.runtime) @Documented @componentpublic @interface Repository {     String value () Default "";}

You can also take a look at the source code of the @service, @Controller, and find that they are annotated with @component, so in the project we can use the @component annotation for all the automated scanning components, Spring will scan all components that have been annotated with @component.

In fact, @Repository, @Service, @Controller Three types of annotations are created to enhance the readability of the code, and you can use different annotations in different application layers, just like the one below.

DAO Layer:

Package Com.lei.customer.dao; Import Org.springframework.stereotype.Repository; @Repositorypublic class Customerdao {    @Override public    String toString () {        return ' Hello, this is Customerda O ";    }    }

Service Layer:

Package com.lei.customer.services; Import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.Service; Import Com.lei.customer.dao.CustomerDAO; @Servicepublic class CustomerService {    @Autowired    Customerdao Customerdao;     @Override public    String toString () {        return "customerservice [customerdao=" + Customerdao + "]";    }}

Spring filter component in auto scanning--filters the components 1 during automatic scanning. Filter Component--include

The following example shows the automatic scanning of registration components with "filter", which, as long as they match the defined "regex" naming rules, do not need to be annotated with @component before Clasee.

DAO layer, Customerdao.java as follows:

Package Com.lei.customer.dao; public class Customerdao {    @Override public    String toString () {        return ' Hello, this is Customerdao ";    }    }

Service layer, Customerservice.java as follows:

Package com.lei.customer.services; Import Org.springframework.beans.factory.annotation.autowired;import Com.lei.customer.dao.CustomerDAO; public class CustomerService {    @Autowired    Customerdao Customerdao;     @Override public    String toString () {        return "customerservice [customerdao=" + Customerdao + "]";    }}

The Spring Filtering,xml is configured as follows:

<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-2.5.xsd    http://www.springframework.org/schema/context    http://www.springframework.org/ Schema/context/spring-context-2.5.xsd ">     <context:component-scan base-package=" Com.lei ">         < Context:include-filter type= "regex"                        expression= "com.lei.customer.dao.*dao.*"/>         <context: Include-filter type= "regex"                        expression= "com.lei.customer.services.*service.*"/>     </context: Component-scan> </beans>

Attention:

In the XML file above, all file names, as long as the DAO and Service (*dao.*,*service.*) keywords are included, will be checked for registration into the spring container.

Run the following code:

Package Com.lei.common; Import Org.springframework.context.applicationcontext;import Org.springframework.context.support.ClassPathXmlApplicationContext; Import Com.lei.customer.services.CustomerService; public class App {public    static void Main (string[] args)    {        ApplicationContext context =         new CLASSPATHXM Lapplicationcontext (new string[] {"Spring-autoscan.xml"});         CustomerService cust = (customerservice) context.getbean ("CustomerService");        SYSTEM.OUT.PRINTLN (Cust);     }}

[Customerdao=hello, this is Customerdao]

2. Filter Component--exclude

You can also use exclude to set up components to avoid being discovered by spring and registered in a container.

The following configuration excludes components that have been commented on with @service

<context:component-scan base-package= "Com.lei.customer" >        <context:exclude-filter type= "annotation"             expression= "Org.springframework.stereotype.Service"/>        </context:component-scan>

The following configuration excludes components that contain the "DAO" keyword

<context:component-scan base-package= "Com.lei" >        <context:exclude-filter type= "regex"             expression = "com.lei.customer.dao.*dao.*"/>        </context:component-scan>

Spring Basic Series 7-automatic scanning of components or beans

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.