Spring Learning notes-Minimizing the spring XML configuration

Source: Internet
Author: User

                                         spring Learning notes-minimizing spring XML configuration

  &NBSP Automatic Assembly (autowiring) helps reduce and even eliminate configuration <property> elements and <constructor-arg> elements. Let spring automatically identify how a bean's dependencies are assembled.
      automatic detection (autodiscovery) is a step closer to automatic assembly, allowing spring to automatically identify which classes need to be configured as spring beans, thereby reducing the use of <bean> elements.
1. Automatic assembly Properties      1.1  4 type automatic assembly          byname--automatically assembles other beans with the same name (or ID) of the bean's properties into the corresponding properties of the bean. If there is no bean that matches the name of the attribute, the property is not assembled.
       bytype--automatically assembles other beans of the same type as the Bean's properties into the corresponding properties of the bean. If there is no bean that matches the type of the attribute, the property is not assembled.
       constructor--automatically assembles other beans of the same type as the Bean's constructor entry into the corresponding entry parameters of the Bean Builder.
       autodetect--first attempts to assemble automatically using constructor. If it fails, try using Bytype for automatic assembly.              byname automatic assembly:

<bean id = "Kenny" class = "com.ouc.test.springs.Instruments" Autowire = "byname" >
   <property name = "Song" V Alue = "Bells"/>
</bean>
Automatically assembles the bean with the same ID as the property's name for the property. Bytype Automatic assembly: If spring looks for multiple beans, and their type matches an automatically assembled attribute type, spring does not guess which Bean is more suitable for automatic assembly, but throws an exception.
You can identify a preferred bean for automatic assembly, or you can cancel the candidacy of a bean for automatic assembly. In order to use the primary property, you have to set the primary property of the non-preferred bean to false.
<bean id = "saxophone" class = "com.ouc.test.springs.Saxophone" primary = "false"/>
The primary property is only meaningful for identifying preferred beans.
If you want to exclude certain beans, you can set the Autowire-candidate property of these beans to false.
<bean id = "saxophone" class = "com.ouc.test.springs.Saxophone" autowire-candidate = "false"/>
Constructor Automatic assembly: If you want to configure the bean through constructor injection, you can remove the <constructor-arg> element, and spring automatically selects the bean injection into the constructor entry in the application context.
<bean id = "saxophone" class= "Com.ouc.springs.test.Saxophone"  Autowire = "constructor"/>
Best Automatic assembly:
<bean id = "saxophone" class= "Com.ouc.springs.test.Saxophone"  autowire = "AutoDetect"/>
1.2 Default automatic assembly
<?xml version= "1.0" encoding= "UTF-8"?> <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-3.1.xsd
     Default-autowire= "Bytype" >
  </beans><span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); > </span>

2. Use annotation assemblyThe spring container defaults to disabling the annotation assembly.
The easiest way to enable annotation assembly is to use the <context:annotation-config> element in spring's context namespace configuration.
Spring 3 supports several different annotations for automatic assembly:
Spring's @autowired annotation with its own;
@inject annotation of JSR-330;
JSR-250 's @resource annotation.
2.1 using @autowired
  @Autowired public
  Void Setinstrument (instrument instrument) {
    this.instrument = instrument;
  }
Spring will attempt to perform Bytype automatic assembly on this method, and you can use @autowired to annotate any method that requires the automatic assembly of the bean Reference.
You can use @autowired annotations to annotate attributes directly and remove setter methods:
  @Autowired
  Private instrument instrument;
1 Optional Automatic assembly:
By default, @Autowired the attributes or parameters that are marked must be assembled. If no bean can be assembled into an attribute or parameter that @autowired is annotated with, automatic Assembly will fail (throw nosuchbeandefinitionexception).
It is optional to configure automatic assembly by setting the @autowired required property to False.
    @Autowired (required=false)
    private instrument instrument;
2) The dependence of the limitation of ambiguity
@Qualifier annotations reduce the range of automated assembly selection candidate beans, narrowing the selection to only one bean by specifying the bean's ID.
    @Autowired
    @Qualifier ("Guitar")
    private instrument instrument;
3 Create a custom qualifier (Qualifier)
    Import Java.lang.annotation.ElementType;
    Import java.lang.annotation.Retention;
    Import Java.lang.annotation.RetentionPolicy;
    Import Java.lang.annotation.Target;
    Import Org.springframework.beans.factory.annotation.Qualifier;

    @Target ({Elementtype.field, elementtype.parameter, elementtype.type})
    @Retention (retentionpolicy.runtime)
    @Qualifier public
    @interface stringedinstrument{}
2.2 Implementation of standards-based automatic assembly with the help of @inject
    @Inject
    Private instrument instrument;
@Inject no Required property.
Qualify the attributes that the @inject is annotated with.
    @Inject
    @Named ("Guitar")
    private instrument instrument;
@Named The Bean's ID to identify the selectable bean, @Named is actually a callout annotated with the @qualifier annotation.
Create a custom JSR-330 Qualifier
    Import Java.lang.annotation.ElementType;
    Import java.lang.annotation.Retention;
    Import Java.lang.annotation.RetentionPolicy;
    Import Java.lang.annotation.Target;
    Import Javax.inject.Qualifier;

    @Target ({Elementtype.field, elementtype.parameter, elementtype.type})
    @Retention (retentionpolicy.runtime)
    @Qualifier public
    @interface stringedinstrument{}
2.3 Use of expressions in annotation injection
     @Value ("#{systemproperties.myfavoritesong}")
     private String song;

3. Automatically detect beans
Automatic detection using the <context:component-scan> element configuration.
<?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-3.1.xsd
      Http://www.springframework.org/schema/context
      http://www.springframework.org/schema/beans/spring-context-3.1.xsd ">

      <context:component-scan Base-package= "Com.ouc.springs.test" >
      </context:component-scan>
   </beans>
3.1 to automatically detect the annotation beanBy default,,<context:component-scan> looks for classes that are annotated with a stereotype (stereotype) annotation, and these special annotations are as follows:
@Component-A common stereotype annotation that identifies the class as a spring component.
@Controller-Identity defines the class as spring MVC Controller.
@Repository-Identity defines the class as a data warehouse.
@Service-Identity defines the class as a service.
Any custom annotations that use the @component annotation.
3.2 filtering Component scanningBy configuring <context:include-filter> and <context:exclude-filter> child elements for <context:component-scan>, you are free to adjust the scan behavior.
<context:component-scan base-package= "Com.ouc.springs.test" >
        <context:include-filter type= " Assignable "expression=" Com.ouc.springs.tst.Instrument "/> <context:exclude-filter type=" annotation "
        expression= "Com.ouc.springs.tst.SkipIt"/>
</context:component-scan>

4. Using spring Java-based configuration 4.1 Define a configuration class
   Import org.springframework.context.annotation.Configuration;

   @Configuration public
   Class springidolconfig{}
@Configuration annotations tell Spring as an identity: This class will contain the definition of one or more spring beans.

4.2 Declaration of a simple bean
   @Bean Public
   Performer Dukes () {return
     new juggler ();
   }
@Bean tell Spring This method returns an object that should be registered as a bean in the spring application context, with the method name as the bean's ID.

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.