Spring for Java EE development, including condition annotation, combination annotation and meta annotation, and javaeespring

Source: Internet
Author: User

Spring for Java EE development, including condition annotation, combination annotation and meta annotation, and javaeespring

In the previous blog, we talked in detail about multithreaded programming and task timer in Spring developed by JavaEE. In this blog, we will talk about condition annotation @ Conditional and combination conditions. The condition annotation simply selects Bean object creation based on specific conditions. Conditional annotation is to make different things according to different conditions. In Spring, condition annotation can be said to be a manifestation of the state pattern in the design pattern and also an Application Part of polymorphism in object-oriented programming. The combination annotation is to combine the existing annotation. The following sections provide a detailed introduction and examples.

 

I. Condition annotation ---- @ Conditional

In this Part of this blog, we will talk about conditional annotations. As the name suggests, conditional annotations can be used to make different things based on different conditions. In Spring, condition annotation can be said to be a manifestation of the state pattern in the design pattern and also an Application Part of polymorphism in object-oriented programming.

In the Spring framework, when we use condition annotations, we create a class for each independent condition, depending on the conditions corresponding to this class, we can select different tasks for execution. Of course, we generally use interfaces to declare a task. Because we will specify the specific class under the specific condition in the Spring configuration class. Next, let's take a look at the specific usage of the @ Conditional annotation in the Spring framework.

Of course, the condition set corresponding to the same Service interface is mutually exclusive, that is to say, only one condition is true under certain circumstances.

 

1. Create service interfaces and specific services

First, create a Service interface, and then create two Service classes based on the interface. Below we will specify different conditions in the configuration class, which will correspond to different Service objects. First, create the Service interface. The code below is the Service interface we created. This interface is simple and has only one description method. In the specific Service class, we will provide the specific implementation of the description () method, and use this method to differentiate implementation of different classes.

package com.zeluli.conditional;public interface ConditinalServiceInteface {    public String description();}

 

After the ServiceInterface is created, we should create a specific class. The FirstConditionService and SecondConditionService classes below both implement the ConditinalServiceInteface interface and provide the specific implementation of the description () method. Later, we will give the corresponding conditions when configuring Bean in the lower class. This section is only the preparation part.

Package com. zeluli. conditional; public class FirstConditionService implements ConditinalServiceInteface {public String description () {return "Service with the first condition ";}} ========================================================== = package com. zeluli. conditional; public class SecondConditionService implements ConditinalServiceInteface {public String description () {return "Service with the second condition ";}}

 

2. Create a condition class corresponding to @ Conditional

After creating the Service interface and Service class, we will create the condition class required for the @ Conditional annotation. Each Condition class corresponds to an independent Condition. The Condition class in Spring needs to implement the Condition interface. Below are the two condition classes we created.

Both Condition classes implement Condition in the Spring framework and provide the matches () method. The Return Value of the matches () method is a Boolean value. If false is returned, the condition corresponding to the condition class is invalid. If true is returned, the condition corresponding to the condition is true. To simplify the operation, set FirstConditional to false, and SecondConditional to true. The implementation of specific condition classes is as follows.

Package com. zeluli. conditional; import org. springframework. context. annotation. condition; import org. springframework. context. annotation. conditionContext; import org. springframework. core. type. annotatedTypeMetadata; public class FirstConditional implements Condition {// public boolean matches (ConditionContext context, AnnotatedTypeMetadata metadata) {return false ;}} ========================================================== = package com. zeluli. conditional; import org. springframework. context. annotation. condition; import org. springframework. context. annotation. conditionContext; import org. springframework. core. type. annotatedTypeMetadata; public class SecondConditional implements Condition {public boolean matches (ConditionContext context, AnnotatedTypeMetadata metadata) {return true ;}}

 

3. Configure conditions in the Java configuration class

After the Service interface, Service class, and corresponding conditions are created, we should associate the condition class with the Service class object in the Java configuration class. The code segment below is the configuration class corresponding to this part. When declaring the Bean of the FirstConditionService class, we use the @ Conditional annotation. The @ Conditional parameter is FirstConditional. class, that is, the object of FirstConditionService will be instantiated only when the conditions of the FirstConditional class are set.

Similarly, SecondConditionService corresponds to SecondConditional. The Code is as follows.

Package com. zeluli. conditional; import org. springframework. context. annotation. bean; import org. springframework. context. annotation. componentScan; import org. springframework. context. annotation. conditional; import org. springframework. context. annotation. configuration; @ Configuration @ ComponentScan ("com. zeluli. conditional ") public class ConditionalConfig {@ Bean @ Conditional (FirstConditional. class) // specify the condition class public FirstConditionService getFirstConditionalService () {return new FirstConditionService () ;}@ Bean @ Conditional (SecondConditional. class) public SecondConditionService getSecondConditionService () {return new SecondConditionService ();}}

 

4. Create the Main method for testing.

Next we have reached the test time. Below we get the context from the above ConditionalConfig configuration class, and then get the corresponding Service object from the context. When getting an object, we use the ConditionalServiceInterface interface to obtain and declare the Bean. That is to say, the object carried by the service variable is the object of a class in all classes that implement the ConditionalServiceInterface interface. When a condition corresponding to a Service class is set, the object of this class is created.

As mentioned above, the conditions corresponding to each class in the ConditionalServiceInterface interface must be mutually exclusive, that is, only one of these conditions is valid under certain circumstances. Because we return true for the second condition, the condition is true, so the SecondConditionalService class object will be called. Therefore, when we call the description () method of the service, we call the corresponding method in the SecondConditionalService class. The details are as follows.

 

  

 

 

2. Combined Annotation

The combination annotation is easy to understand. It is to combine multiple annotations to generate a new annotation. Using this new annotation is equivalent to using all the annotations in this combination annotation. This feature is quite useful. Next we will look at how to create and use composite annotations.

 

1. Create a combination of annotations

Next we will look at how to combine multiple annotations into one piece through a simple example. In the previous Spring Configuration class, we often use the @ Configuration and @ ComponentScan annotations. Next, we combine and encapsulate them to form a new annotation.

The CombinationConfiguration annotation below is the New Annotation of our combination. The annotation uses @ Configuration and @ ComponentScan for modification, it also indicates that the @ CombinationConfiguration annotation has the functions of both the @ Configuration and @ ComponentScan annotations.

package com.zeluli.combination.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Configuration@ComponentScanpublic @interface CombinationConfiguration {    String[] value() default{};}

 

2. Use of combined annotations

After the corresponding comments are created, it is time to use them. The usage of the annotations above is no different from that of the general annotations. Only this annotation indicates the two annotations @ Configuration and @ ComponentScan previously written. The code below shows how to use the annotation combination.

  

 

OK, today's blog will come here, github source code share address: https://github.com/lizelu/SpringDemo

 

Related Article

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.