Spring Practical Note 4---Spring's custom assembly and automatic detection

Source: Internet
Author: User

Spring Automatic assembly and auto-detection is to minimize the spring XML configuration, if we have a lot of beans to assemble into the spring container, then our configuration file will look very long, people feel dizzy, proper use of automatic assembly and auto-detection, will help alleviate the problems mentioned above


* Automatic assembly: (autowiring) helps reduce or even eliminate configuration <property> elements and <constructor-arg> elements, allowing spring to automatically identify how to assemble bean dependencies.

* Automatic detection: (autodiscovery) further than automatic assembly, so that spring can automatically identify which classes need to be assembled into Springbean to reduce the use of <bean> elements


Automatic assembly

Spring provides four ways to assemble automatically

* ByName automatically assemble other beans whose attributes have the same name into the corresponding attributes of the bean

* Bytype The corresponding attributes of the bean automatically assembled with other beans of the same type as the Bean's attributes

* constructor automatically assembles other beans with the same type as the bean's constructor into the corresponding entry parameters of the constructor

*autodetect first try to use constructor for automatic assembly, if it fails, then use Bytype for automatic assembly


ByName

<bean id= "Kenny2" class= "xxx.xxx.xxx" >  <property name= "song" Value= "Jingle Bells"/>  < Property name= "instrument" ref= "saxophone"/></bean><!--The following is the use of automatic assembly, assuming that the ID defined here is Instrument--><bean Id= "instrument" class= "xxx.xxx.xxx"/><bean id= "Kenny" class= "Xxx.xxx.xxx" autowire= "byname" >  < Property Name= "Song" Value= "Jingle Bells"/></bean>


Let's look at the difference between the two configurations, the value of the property instrument is a bean that has already been defined in that context, the reference is its ID, and the second method changes the bean's ID to the same name as the Bean property that references it. Then use the byname way to automatically assemble, you can see the second assembly, we do not display the value of the setting instrument, but the first time when the bean is called, the system automatically matches the bean with the same name as this property from the dynamic assembly, in this way to simplify the configuration of the XML.


Bytype

<bean id= "Kenny" class= "Xxx.xxx.xxx" autowire= "Bytype" >  <property name= "song" Value= "Jingle Bells"/> </bean>

You only need to change the value of the Autowire property to Bytype, but in the context of the application, if there are multiple bean types that match the Bean's auto-assembly properties, then an error occurs because the Bytype method allows only one bean of the same type to be matched. If there are more than one bean of the same type in the application context, spring provides two other options, either to set a preferred bean or to exclude some beans.


The primary property of the <bean> element represents whether it is the preferred bean, and if the label is true, the bean will be the preferred bean, but spring defaults to the primary property of each bean for City true, Therefore, if you need to set the preferred bean, you need to label those non-preferred beans with the primary property as false.

If we want to exclude certain beans during the automatic assembly process, use the Autowire-candidate property set to False.

Look at the following code

<bean id= "Kenny" class= "Xxx.xxx.xxx" autowire= "Bytype" primary= "false" >  <property name= "song" Value= " Jingle Bells "/></bean><pre name=" code "class=" HTML "><bean id=" Kenny "class=" Xxx.xxx.xxx "autowire= "Bytype" autowire-candidate= "false" >  <property name= "song" Value= "Jingle Bells"/></bean>

The above two examples represent the two options described above, respectively.

Constructor

<bean id= "Kenny" class= "Xxx.xxx.xxx" autowire= "constructor" >  <property name= "song" Value= "Jingle Bells" /></bean>
Constructor Auto-Assemble simply set the Autowire property to constructor, which eliminates the declaration <constructor-arg> element


Best Automatic assembly (AutoDetect)

<bean id= "Kenny" class= "Xxx.xxx.xxx" autowire= "AutoDetect" >  <property name= "song" Value= "Jingle Bells"/ ></bean>
First use constructor if the failure, is to use Bytype, the use of the same method as described above is the same, there is not much to say


Default Automatic assembly

If in one configuration file all the assemblies use the same automatic configuration, it is cumbersome to add a Autowire property to each bean declaration, and to avoid such duplication, the default automatic assembly can be used.

Using the default automatic assembly method is to add a Default-autowire attribute to the <beans> element, and after adding this property, the automatic assembly in the configuration file will be assembled by default, if there is an individual bean that needs to be used in another way, Setting the Autowire property directly on the bean will override the default automatic assembly configuration, as shown in the code below.

  <beans ... Default-autowire= "Bytype" ></beans>


Assembling with annotations

Before using the annotation assembly, the first way to turn on the annotation assembly is to add the following sentence in the configuration file

<context:annotation-config>

The premise, of course, is to add the context namespace

Spring supports a variety of annotation assembly methods, here is a brief introduction of spring's own annotated assembly


Using @autowired annotations

This note can be used almost any method, as long as the method requires automatic assembly parameters can not necessarily be setter method, but is generally used in setter methods and constructors, see the following code

@Autowiredpublic void Setinstrument (instrument instrument) {    this.instrument = instrument;}
The above code is to put the @autowired annotation on the setter method, when spring creates the bean of the class, it will automatically look for matching parameters injected into the bean, but the parameters need to be assembled in the context of the application at the same time, otherwise it is not found.

@Autowired Another usage is the annotation constructor

@Autowiredpublic instrumentalist (instrument instrument) {    this.instrument = instrument;}

@Autowired another use is to directly annotate the attribute, thus removing the setter method

@Autowiredprivate instrument instrument;

Note: The @Autowired must be used when only one bean is suitable for assembly into the attributes or parameters marked by the @autowired annotation, otherwise spring throws an exception if the corresponding bean is not found in the application context and is automatically assembled. Spring also throws an exception (nosuchbeandefinitionexception), and if you want to avoid this, and the properties that need to be assembled are not required to be assembled, you can use the following code to work with annotations

@Autowired (Required=false) Private instrument instrument;
Add @autowired's Required property here, set this property to False, which means that the property is not required when the bean is created


@Qualifier annotations

If there are two beans that must exist in the same application context, but the automatic assembly requires only one assembly, this time you can use the @qualifier annotation to specify a bean to assemble so that it does not report an exception.

@Autowired @qualifier ("Guitar") private instrument instrument;
The strings in parentheses are labeled with the ID of the bean that needs to be automatically assembled.



using an expression in annotation injection

In the process of automatic assembly using annotations, you can use @value annotations if you want to automatically assemble the parameters of a basic type or a literal constant.

@Value ("eruption") private String song;
The automatic assembly here assembles a string type of value for a property of type string, and can also assemble properties of basic types such as Int,boolean.


In @value annotations, we can use expressions to dynamically calculate and assemble values for properties such as using a spel expression to get a value from a system property

@Value ("#{systemproperties.myfavoritesong}") Private String song;


Automatically detect beans

Automatic detection allows spring to automatically scan the beans that need to be assembled into the container from the specified care, but before using it, the automatic assembly needs to be turned on, which requires the following code to be configured in the Spring configuration file

<context:component-scan base-package= "Com.springinaction.springidol" ></context:component-scan>
In this configuration, Spring automatically detects all classes that Com.springinaction.springidol can register as Springbean, and then automatically generates the corresponding bean.

You can use the following annotations to identify which classes are classes that can be automatically registered as Springbean


* @Component generic stereotype annotations that identify the class as a spring component

* @Controller identity defines the class as a spring MVC controller

* @Repository identity defines the class as a data warehouse (this annotation can be used when using the database)

* @Service identity defines the class as a service

* Use any of the custom annotations marked with @component

@Componentpublic class Guitar implements instrument{public    void Play () {        System.out.println ("...");}    }
In this scenario, the Guitarbean ID will be set to the default guitar


You can specify the bean ID in the @component annotation

@Component ("Eddie") public class Guitar implements instrument{public    void Play () {        System.out.println ("... ");    }}
This will change the ID of the bean in the spring container to Eddie.


Spring automatic detection also contains a non-practical annotation of the automatic detection rules, the rules in the future in the application of the time to introduce, here does not introduce too much


Spring Practical Note 4---Spring's custom assembly and automatic detection

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.