spring--Configuring Beans with annotations

Source: Internet
Author: User

Spring Configures beans with annotations
Configuring beans based on annotations
To configure the Bean's properties based on annotations

Scanning components in the Classpath
Component scanning (component scanning): Spring is able to automatically scan, detect and instantiate components with specific annotations from the classpath.
Specific components include the following:
[Email protected]: basic annotations that identify a component that is managed by spring
[Email protected]: Identify the persistence layer component
[Email protected]: Identify service layer (business layer) components
[Email protected]: Identify presentation layer components
For scanned components, spring has a default naming policy: Use unqualified class name, first letter lowercase. You can also identify the name of a component in the annotation by its Value property.
When a specific annotation is used on a component class, the <CONTEXT:COMPONENT-SCAN&GT is also declared in the Spring configuration file:
The Base-package property specifies a base class package that needs to be scanned, and the spring container will scan all classes in the base class package and its child packages
When you need to scan multiple packages, you can use commas to separate
If you want to scan only specific classes, not all classes under the base package, you can use the Resource-pattern property to filter specific classes, for example:
<CONTEXT:COMPONENT-SACN base-package= "Com.yl.spring.beans" resource-pattern= "Autowire/*.class"/>
<context:include-filter> child nodes represent the target classes to be included
<context:exclude-filter> child nodes indicate the target class to exclude
<context:component-sacn> can have a number of <context:include-filter> and <context:exclude-filter> sub-nodes


<context:include-filter> and <context:exclude-filter> sub-nodes support multiple types of filter expressions:

category Example description
annotation  com.yl.XxxAnnotation all annotated Xxxannotati On class that filters
assinable  If the target class is annotated with an annotation; com.yl.XxxService all inherit or extend XXX The class of the Service, which takes the target class whether to inherit or extend a particular class for filtering
aspectj  com.yl.*service name of all classes Service-terminated classes and classes that inherit or extend them, which are filtered by the ASPECTJ expression
regex  com.yl.anno.* all C The class under the Om.yl.anno package. The type uses regular expressions to filter
custom  According to the class name of the class, com.yl.xxxtypefilter  with Xxxtype Filter defines the filtering principle in the code way. The class must implement the Org.springframework.core.type.TypeFilter interface


Component Assembly
The <context:component-scan> element also automatically registers the Autowiredannotationbeanpostprocessor instance, which can be automatically assembled with @autowired and @resource, and @inject Properties of annotations

Automatically assemble beans using @autowired
@Autowired annotations automatically assemble individual bean properties with compatible types
-Constructors, normal fields (even non-public), all methods with only parameters can be applied @autowired
-By default, all properties that use the @autowired annotation need to be set, and the exception is thrown when spring cannot find a matching Bean assembly property. If a property is allowed to not be set, the required property of the @autowired annotation can be set to False
-By default, automatic assembly by type will not work when there are multiple type-compatible beans in the IOC container. The name of the bean can be provided in the @qualifiter annotation at this time, and spring allows the parameter callout of the method @Qualifiter the name of the injected bean specified
[Email protected] annotations can also be applied to attributes of an array type, at which time spring will automatically match all matching beans
[Email protected] annotations can also be applied on collection properties, when spring reads the type information for that collection, and then automatically assembles all of the beans that are compatible with it
[Email protected] When the annotation is used on JAVA.UTIL.MAP, if the map's key value is a string, spring automatically assembles the bean that is compatible with the map value type, at which point the bean's name is used as the key value

Testobject.java

1  Package com.yl.annotation; 2 3 Import org.springframework.stereotype.Component; 4 5 @Component 6  Public class Testobject {7     8 }

Userrepository.java interface

1  Package com.yl.annotation.repository; 2 3  Public Interface userrepository {4      Public void save (); 5     6 }

Userrepositoryimpl.java

1  Packagecom.yl.annotation.repository;2 3 Importorg.springframework.beans.factory.annotation.Autowired;4 Importorg.springframework.stereotype.Repository;5 6 ImportCom.yl.annotation.TestObject;7 8 @Repository9 //@Repository ("Userrepository")Ten  Public classUserrepositoryimplImplementsUserrepository { One      A@Autowired (required=false) -     PrivateTestobject Testobject; -      the @Override -      Public voidSave () { -System.out.println ("Userrepository save ..."); - System.out.println (testobject); +     } -  +}

Userjdbcrepository.java

1  Packagecom.yl.annotation.repository;2 3 Importorg.springframework.stereotype.Repository;4 5 @Repository6  Public classUserjdbcrepositoryImplementsUserrepository {7 8 @Override9      Public voidSave () {TenSystem.out.println ("Userjdbcrepository save ..."); One     } A  -}

Userservice.java

1  PackageCom.yl.annotation.service;2 3 Importorg.springframework.beans.factory.annotation.Autowired;4 ImportOrg.springframework.beans.factory.annotation.Qualifier;5 ImportOrg.springframework.stereotype.Service;6 7 Importcom.yl.annotation.repository.UserRepository;8 9 @ServiceTen  Public classUserService { One @Autowired A@Qualifier ("Userjdbcrepository") -     Privateuserrepository userrepository; -      the     /*@Autowired - @Qualifier ("Userjdbcrepository") - Public void Setuserrepository (Userrepository userrepository) { - this.userrepository = userrepository; +     }*/ -      +      Public voidAdd () { ASystem.out.println ("UserService add ..."); at Userrepository.save (); -     } -}

Usercontroller.java

1  PackageCom.yl.annotation.controller;2 3 Importorg.springframework.beans.factory.annotation.Autowired;4 ImportOrg.springframework.stereotype.Controller;5 6 ImportCom.yl.annotation.service.UserService;7 8 @Controller9  Public classUsercontroller {Ten @Autowired One     PrivateUserService UserService; A      -      Public voidExecute () { -System.out.println ("Usercontroller execute ..."); the Userservice.add (); -     } -}

Beans-annotation.xml

1 <?XML version= "1.0" encoding= "UTF-8"?>2 <Beansxmlns= "Http://www.springframework.org/schema/beans"3 Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"4 Xmlns:context= "Http://www.springframework.org/schema/context"5 xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 6 Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-4.1.xsd ">7 8     <!--Specify packages scanned by the spring IOC container -9     <!--the scanned resource can be specified by Resource-pattern -Ten     <!--<context:component-scan One base-package= "Com.yl.annotation" A resource-pattern= "Repository/*.class" ></context:component-scan> - -      -     <!--Context:exclude-filter Sub-nodes specify which components to exclude from the specified expression -     the     <!--The context:include-filter child node Specifies the component that contains the specified expression, which needs to be used use-default-filters mates -     -     <Context:component-scan -         Base-package= "Com.yl.annotation" > -         <!--use-default-filters= "false" > - +         <!--<context:exclude-filter type= "annotation" - expression= "Org.springframework.stereotype.Repository"/> - +          A         <!--<context:include-filter type= "annotation" at expression= "Org.springframework.stereotype.Repository"/> - -              -         <!--<context:exclude-filter type= "assignable" - expression= "Com.yl.annotation.repository.UserRepository"/> - -          -         <!--<context:include-filter type= "annotation" in expression= "Com.yl.annotation.repository.UserRepository"/> - -     </Context:component-scan> to </Beans>

Automatically assemble beans using @resource or @inject
Spring also supports @resource and @inject annotations, which are similar to the functions of @autowired annotations
@Resource annotations require a property of the bean name, and if the property is empty, the variable or method name at the label is automatically used as the bean's name
@Inject and @autowired annotations are also beans injected by type, but no required property
Recommended use of @autowired annotations

spring--Configuring Beans with annotations

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.