@ConditionalOnExpression注解的使用示例

以下是一个关于 @ConditionalOnExpression 注解的使用示例:

假设我们有一个应用,根据配置文件中的属性来决定是否启用某个特定的功能模块。

1. 创建一个实体类:

package com.example.demo.entity;

public class SpecialFeature {

    private boolean enabled;

 

    public SpecialFeature(boolean enabled) {

        this.enabled = enabled;

    }

    public boolean isEnabled() {

        return enabled;

    }

}

 

 

2. 创建配置类:

 

package com.example.demo.config;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Conditional;

 

@Configuration

public class AppConfig {

 

    @Bean

    @ConditionalOnExpression("${enable.special.feature:true}")

    public SpecialFeature specialFeature() {

        return new SpecialFeature(true);

    }

}

在这个配置类中,只有当配置文件中的属性 enable.special.feature 为 true 时,才会创建 SpecialFeature 这个 Bean。

 

3. 测试类(如果需要测试):

package com.example.demo;

 

import com.example.demo.config.AppConfig;

import com.example.demo.entity.SpecialFeature;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

 

@SpringBootTest(classes = AppConfig.class)

class DemoApplicationTests {

 

    @Autowired

    private SpecialFeature specialFeature;

 

    @Test

    void contextLoads() {

        if (specialFeature.isEnabled()) {

            System.out.println("Special feature is enabled.");

        } else {

            System.out.println("Special feature is disabled.");

        }

    }

}

在上述示例中,如果在配置文件(如 application.properties 或 application.yml )中设置了 enable.special.feature=true ,那么在运行测试或启动应用时,会创建 SpecialFeature 实例并且打印“Special feature is enabled.”;如果设置为 false 或未设置该属性,那么不会创建 SpecialFeature 实例。

这样就通过 @ConditionalOnExpression 注解根据配置文件中的属性实现了动态的条件判断来决定是否创建特定的 Bean。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值