以下是一个关于 @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。