In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
In this article, the editor introduces in detail "how to use Spring Boot condition notes". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to use Spring Boot condition notes" can help you solve your doubts.
Foreword:
The SpringBoot condition annotation @ Conditional can be used to determine whether a particular Bean needs to be created based on a particular condition. Conditional annotations are widely used in the SpringBoot autoconfiguration function. Next, let's make a brief introduction to the use of @ Conditional.
The @ Conditional annotation needs to be used with the Condition interface. Tell whether the matching condition is met by the corresponding Condition interface.
@ Target ({ElementType.TYPE, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Documentedpublic @ interface Conditional {/ * all Condition interfaces used for matching (classes that implement this interface) are considered to satisfy the condition * / Class [] value () default {} only if these classes return true. / * Class.getName () * / String [] type () default {}; / * (used to specify the annotation modified Bean) the annotation class required for the condition * / Class [] parameterizedContainer () default {};} 1.1.2 @ ConditionalOnMissingBean
The Condition implementation class corresponding to @ ConditionalOnMissingBean is OnBeanCondition. Takes effect if the specified Bean does not exist in the Spring container.
@ ConditionalOnMissingBean configuration parameters
@ Target ({ElementType.TYPE, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Conditional (OnBeanCondition.class) public @ interface ConditionalOnMissingBean {/ * Class object array of classes that need to be conditional * / Class [] value () default {}; / * * Name of classes that need to be conditional, Class.getName () * / String [] type () default {} / * * the array of Class objects to be ignored when matching Bean, which is generally the parent class * @ ConditionalOnMissingBean (value = JdbcFactory.class, ignored = MySqlDefaultFactory.class) * / Class [] ignored () default {}; / * the Name of the class to be ignored when matching Bean, Class.getName () / String [] ignoredType () default {} / * (used to specify the Bean modified by the annotation) the annotation class required for the condition * / Class [] parameterizedContainer () default {};}
For example, in the following example, when there is no Bean for redisTemplate in the container, a RedisTemplate will be created and added to the container.
@ Bean @ ConditionalOnMissingBean (name = "redisTemplate") public RedisTemplate redisTemplate (RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {RedisTemplate template = new RedisTemplate (); template.setConnectionFactory (redisConnectionFactory); return template;} 1.1.3 @ ConditionalOnSingleCandidate
The Condition processing class corresponding to @ ConditionalOnSingleCandidate is OnBeanCondition. Takes effect if you specify that there is only one Bean in the container, or if you specify the preferred Bean, although there are multiple.
@ ConditionalOnSingleCandidate configuration parameters
@ Target ({ElementType.TYPE, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Conditional (OnBeanCondition.class) public @ interface ConditionalOnSingleCandidate {/ * Class object of the class that needs to be conditional * / Class value () default Object.class; / * Name of the class that needs to be conditional, Class.getName () * / String type () default "" / * search container level, current container, parent container * / SearchStrategy search () default SearchStrategy.ALL;} 1.2 class as condition 1.2.1 @ ConditionalOnClass
The Condition processing class corresponding to @ ConditionalOnClass is OnClassCondition. Takes effect if there is a specified class under the current classpath.
Introduction to @ ConditionalOnClass configuration properties
@ Target ({ElementType.TYPE, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Conditional (OnClassCondition.class) public @ interface ConditionalOnClass {/ * Class object array of classes that need to be conditional * / Class [] value () default {}; / * * Name of classes that need to be conditional, Class.getName () * / String [] name () default {};} 1.2.2 @ ConditionalOnMissingClass
The Condition processing class corresponding to @ ConditionalOnMissingClass is OnClassCondition. Takes effect if there is no specified class under the current classpath.
@ Target ({ElementType.TYPE, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Conditional (OnClassCondition.class) public @ interface ConditionalOnMissingClass {/ * Name of the class that needs to be a condition, Class.getName () * / String [] value () default {};} 1.3 SpEL expression as condition
The Condition processing class corresponding to @ ConditionalOnExpression is OnExpressionCondition. Takes effect only if the SpEL expression satisfies the condition.
@ Retention (RetentionPolicy.RUNTIME) @ Target ({ElementType.TYPE, ElementType.METHOD}) @ Documented@Conditional (OnExpressionCondition.class) public @ interface ConditionalOnExpression {/ * SpEL expression to be conditional * / String value () default "true";}
For example, @ ConditionalOn_Expression ("${test.enabled:true}") takes effect only if test.enabled:true exists in the configuration file.
For more detailed usage, take a look at the use of SpEL expressions.
1.4 JAVA version as a condition of judgment
The Condition processing class corresponding to @ ConditionalOnJava is OnJavaCondition. The corresponding JAVA will be created only if the specified Bean version condition is met.
@ Target ({ElementType.TYPE, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Conditional (OnJavaCondition.class) public @ interface ConditionalOnJava {/ * comparison, Range.EQUAL_OR_NEWER: the current version is equal to or higher, Range.OLDER_THAN: the current version is older, the older the version, the older * / Range range () default Range.EQUAL_OR_NEWER / * specify JAVA version * / JavaVersion value (); / * Range options. * / enum Range {/ * * Equal to, or newer than the specified {@ link JavaVersion}. * / EQUAL_OR_NEWER, / * * Older than the specified {@ link JavaVersion}. * / OLDER_THAN}} 1.5 configure attributes as a judgment condition
The Condition implementation class OnPropertyCondition for @ ConditionalOnProperty. Takes effect only if the corresponding configuration property is equal to the value of the given condition.
@ Retention (RetentionPolicy.RUNTIME) @ Target ({ElementType.TYPE, ElementType.METHOD}) @ Documented@Conditional (OnPropertyCondition.class) public @ interface ConditionalOnProperty {/ * value corresponding to property name * / String [] value () default {}; String [] name () default {}; / * property name prefix, optional * / String prefix () default "" / * is used in combination with name to compare whether the obtained attribute value is the same as the value given by havingValue before loading the configuration * / String havingValue () default ""; / * whether it can be loaded if the property is missing. If it is true, the property will load normally without it; otherwise, it will report an error * / boolean matchIfMissing () default false;}.
@ ConditionalOnProperty (prefix = "spring.aop", name = "auto", havingValue = "true") indicates that the corresponding Bean will only be loaded when the spring.aop.auto=true is in the configuration file.
1.6 the existence of resource files as a condition for judgment
The Condition processing class OnResourceCondition for @ ConditionalOnResource. Takes effect only if the specified resource file appears in the classpath.
@ ConditionalOnResource configuration Properties
@ Target ({ElementType.TYPE, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Conditional (OnResourceCondition.class) public @ interface ConditionalOnResource {/ * the name of the resource file to be used as a condition @ ConditionalOnResource (resources= "mybatis.xml") * / String [] resources () default {};} 1.7 whether Web is applied as a condition 1.7.1 @ ConditionalOnWebApplication
The Condition processing class corresponding to @ ConditionalOnWebApplication is OnWebApplicationCondition. Takes effect only if the current project is a Web project.
@ Target ({ElementType.TYPE, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Conditional (OnWebApplicationCondition.class) public @ interface ConditionalOnWebApplication {/ * required type of Web application required as a condition * / Type type () default Type.ANY; / * Available application types. * / enum Type {/ * any web application will match * / ANY, / * only servlet-based Web applications will match * / SERVLET / * * only reactive Web applications will match * / REACTIVE}} 1.7.2 @ ConditionalOnNotWebApplication
The Condition processing class corresponding to @ ConditionalOnNotWebApplication is OnWebApplicationCondition. Takes effect only if the current project is not a Web project.
@ Target ({ElementType.TYPE, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Conditional (OnWebApplicationCondition.class) public @ interface ConditionalOnNotWebApplication {} two @ Conditional customization
The Condition implementation class corresponding to each annotation is specifically mentioned when each extension annotation is introduced above. We can actually emulate these Condition implementation classes to implement our own @ Conditional annotations. Let's take a look at how to implement our own @ Conditional extension annotation with two simple examples.
2.1 determine whether to configure the specified attribute
Note: unlike @ ConditionalOnProperty, @ ConditionalOnProperty determines whether there is an attribute and whether the value is equal to the value we specify. The annotation we are going to implement only determines whether there is a configuration property, regardless of the corresponding value of the property.
Extend the annotation ConditionalOnPropertyExist. Specify our Condition implementation class OnPropertyExistCondition. And specify two parameters. One is that the parameter name is used to specify the property. The other parameter, exist, is used to specify whether it exists or not.
@ Retention (RetentionPolicy.RUNTIME) @ Target ({ElementType.TYPE, ElementType.METHOD}) @ Documented@Conditional (OnPropertyExistCondition.class) public @ interface ConditionalOnPropertyExist {/ * the corresponding key * / String name () default "" in the configuration file; / * whether it is configured or not, it is judged to pass * / boolean exist () default true;}
The OnPropertyExistCondition class simply determines whether the attribute exists or not.
Public class OnPropertyExistCondition implements Condition {@ Override public boolean matches (ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {Map annotationAttributes = annotatedTypeMetadata.getAnnotationAttributes (ConditionalOnPropertyExist.class.getName ()); if (annotationAttributes = = null) {return false;} String propertyName = (String) annotationAttributes.get ("name"); boolean values = (boolean) annotationAttributes.get ("exist"); String propertyValue = conditionContext.getEnvironment (). GetProperty (propertyName) If (values) {return! StringUtils.isEmpty (propertyValue);} else {return StringUtils.isEmpty (propertyValue);} 2.1 determine whether to configure the specified attribute
We simply implement the function of loading different Bean according to the specified system.
@ Retention (RetentionPolicy.RUNTIME) @ Target ({ElementType.TYPE, ElementType.METHOD}) @ Documented@Conditional (OnSystemCondition.class) public @ interface ConditionalOnSystem {/ * specify system * / SystemType type () default SystemType.WINDOWS / * system type * / enum SystemType {/ * windows system * / WINDOWS, / * linux system * / LINUX, / * mac system * / MAC}} public class OnSystemCondition implements Condition {@ Override public boolean matches (ConditionContext context) AnnotatedTypeMetadata metadata) {Map annotationAttributes = metadata.getAnnotationAttributes (ConditionalOnSystem.class.getName ()) If (annotationAttributes = = null) {return false;} ConditionalOnSystem.SystemType systemType = (ConditionalOnSystem.SystemType) annotationAttributes.get ("type"); switch (systemType) {case WINDOWS: return context.getEnvironment (). GetProperty ("os.name"). Contains ("Windows") Case LINUX: return context.getEnvironment (). GetProperty ("os.name"). Contains ("Linux"); case MAC: return context.getEnvironment (). GetProperty ("os.name"). Contains ("Mac");} return false }} after reading this, the article "how to use Spring Boot conditional Notes" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.