search
HomeJavajavaTutorialWhat is the @Conditional annotation in SpringBoot? how to use?

This article brings you what is the @Conditional annotation in SpringBoot? how to use? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Some features of the @Conditional annotation have been used in recent projects, so I wrote this article to record

What is @Conditional?

What is the @Conditional annotation? It can load different beans according to the conditions set in the code. For example, when an interface has two implementation classes, we usually hand over the interface to Spring for management. Only one of the implementation classes will be chosen to implement. We can't use if-else at this time, so the @Conditional annotation appears.

How do I use it?

In SpringBoot, @Conditional annotations are not alone, they are a family. Let’s take a look at several of their members and how they are used

@ ConditionalOnBean
Sample code

@Bean
@ConditionalOnBean(RedisConnectionFactory.class)
   public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
       RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
       template.setConnectionFactory(connectionFactory);
       template.setKeySerializer(new StringRedisSerializer());
       template.afterPropertiesSet();
       return template;
   }

The @ConditionalOnBean annotation is added to this method, and the attribute in the annotation is RedisConnectionFactory. What it means is that if you configure the relevant configuration information of redis, then I will instantiate the RedisTemplate for you to operate. If you do not configure the relevant configuration of redis, then I will not instantiate it (after all, even if there is no configuration, instantiation will report an error. )
Not only that, you can also play like this:

According to the name of the bean @ConditionalOnMissingBean(name = “connectionFactory”) or @ConditionalOnMissingBean(annotation = EnableSyjRateLimit.class), you can perform various operations based on annotations and so on.

  1. @ConditionalOnMissingBean
    This is just one more Missing than 1. What does it mean? As the name suggests, it is instantiated when a certain bean does not exist.

  2. @ConditionalOnClass (A Bean will be instantiated only when a certain class exists)

  3. @ConditionalOnMissingClass (When a certain class does not exist, Only then will a Bean be instantiated)

  4. @ConditionalOnProperty(prefix = “syj”, name = “algorithm”, havingValue = “token”)
    This is a little more complicated. What it means is that when there is an attribute prefixed with syj in the configuration file, the attribute name is algorithm, and then its value is token, a class will be instantiated.

    And this one also has a better attribute
    @ConditionalOnProperty(prefix = “syj”, name = “algorithm”, havingValue = “counter”, matchIfMissing = true)
    What does matchIfMissing mean? That is to say, if all are not satisfied, it will be implemented by default, regardless of whether the attribute syj.algorithm is equal to counter

  5. @ConditionalOnJava (if it is a Java application)

  6. @ConditionalOnWebApplication (if it is a Web application)
    In fact, when it comes to the members of the @Conditional family, we have only talked about a small part of them
    There are probably so many family members:
    What is the @Conditional annotation in SpringBoot? how to use?
    If you want to know more about children's shoes, you can refer to this package
    org.springframework.boot.autoconfigure.condition

Although you talked a lot above, I still Not satisfied

Why are you not satisfied? In fact, there are many reasons. For example, you have not used SpringBoot, and you want to customize it. So what should we do at this time? Let’s customize one.

First customize a rule class

public class MyCondition implements Condition    
{    
      
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata)    
    {    
    		//在这里写你的逻辑,比如说你想a>0时实例化类A,a<0时不实现
        return a>0;    
    }    
}

Then you can use it

@Bean
    @Conditional(MyCondition.class)
    public A a(){
    	return new A()
    }

The above is the detailed content of What is the @Conditional annotation in SpringBoot? how to use?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment