Spring Boot中SessionFactory Bean不存在时,如何阻止GetEntityHandler实例化?
如何让Spring组件仅在特定Bean存在时才创建?
这个问题很典型,Spring Boot提供了现成的条件注解来解决这种依赖Bean存在性的组件创建控制问题,给你两种常用的方案:
方案一:使用@ConditionalOnBean直接依赖SessionFactory的存在
直接在GetEntityHandler类上添加@ConditionalOnBean注解,指定SessionFactory类型。这样Spring容器只有在检测到SessionFactory Bean存在时,才会创建GetEntityHandler实例,完美避免依赖缺失的报错:
@Component @ConditionalOnBean(SessionFactory.class) public class GetEntityHandler implements VoidTreeNodeHandler { private final SessionFactory sessionFactory; @Autowired public GetEntityHandler(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public void handle(TreeContext context, Map<String, Object> parameters) { //do smth } }
这种方式的优势是灵活:不管SessionFactory是通过你的Starter创建,还是其他方式(比如手动注册)进入容器,只要这个Bean存在,GetEntityHandler就会被创建;反之则不会。
方案二:使用@ConditionalOnProperty与Starter的配置条件对齐
既然你的SessionFactory是当clusterj.connectString和clusterj.dataBaseName配置存在时才创建的,你可以让GetEntityHandler复用同一个条件注解,确保两者的创建逻辑完全同步:
@Component @ConditionalOnProperty(prefix = "clusterj", name = {"connectString", "dataBaseName"}) public class GetEntityHandler implements VoidTreeNodeHandler { private final SessionFactory sessionFactory; @Autowired public GetEntityHandler(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public void handle(TreeContext context, Map<String, Object> parameters) { //do smth } }
这种方式的优势是强绑定:只有当Starter的必要配置齐全时,才会创建GetEntityHandler,和SessionFactory的触发条件完全一致,不会出现配置满足但Bean没创建的意外情况。
两种方案都能解决你的问题,你可以根据自己的需求选择:如果希望组件依赖的是Bean本身的存在,选方案一;如果希望严格和配置条件绑定,选方案二。
内容的提问来源于stack exchange,提问作者All_Safe
相关产品推荐
相关产品推荐

