在Spring Boot中,@ConditionalOnProperty注解来控制Bean的创建和加载.
@ConditionalOnProperty注解的使用方法很简单,只需将去添加到类上面即可,使用如下:
import org.springframework.context.annotation.ConditionalOnProperty;
import org.springframework.stereotype.Component;
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
@Component
public class Demo {
// 实现功能A的代码
}
首先,在用户模块的配置文件(例如application.yml)中添加如下配置:
feature:
enabled: true
当用户的"feature.enabled"属性都设置为"true"时,Spring容器会分别创建并加载Demo类的实例。如果其中任何一个模块的"feature.enabled"属性被设置为"false",则对应的实例将不会被创建和加载。这使得应用程序可以根据实际需求灵活地加载和启用功能。