Use of Spring @Conditional annotations

Source: Internet
Author: User

Spring boot is powerful because it uses the new features of the Spring 4 framework: @Conditional annotations, which enable some configurations only if certain conditions are met.

Here's how to use condition


First write a class

Package com.test.spring;

Import org.springframework.context.annotation.Condition;
Import Org.springframework.context.annotation.ConditionContext;
Import Org.springframework.core.type.AnnotatedTypeMetadata;

public class Mycondition implements Condition
{
	/**
	 * Write your own logic here, only return true to enable configuration */
	 public
	Boolean Matches (Conditioncontext context, annotatedtypemetadata Metadata)
	{
		return true;
	}
}

The next step is to use the

Package com.test.spring;

Import java.io.Serializable;

Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Conditional;
Import org.springframework.context.annotation.Configuration;

@Configuration
@Conditional (mycondition.class) Public
class Config
{
	@Bean
	public Serializable createserializable ()
	{
		System.out.println ("======000");
		Return "";
	}
}

@Conditional (Mycondition.class)

This code can be labeled on the class, indicating that all @bean under the class are enabled for configuration

can also be labeled on the method, just enable configuration for the method


In addition to your own custom condition, Spring provides a lot of condition for us

@ConditionalOnBean (a bean is instantiated only if an object exists in the current context)
@ConditionalOnClass (a class is located on the classpath to instantiate a bean)
@ConditionalOnExpression (a bean is instantiated only when the expression is true)
@ConditionalOnMissingBean (a bean is instantiated only if an object does not exist in the current context)
@ConditionalOnMissingClass (a bean is instantiated only if it does not exist on a class path)
@ConditionalOnNotWebApplication (not web App)


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.