如果没有使用spring-boot-starter的依赖bean,请不要注册组件

时间:2019-05-30 09:39:50

标签: java spring spring-boot

我创建spring-boot-starter,它注册了一些bean:

@Configuration
@EnableConfigurationProperties(ClusterJProperties.class)
@ConditionalOnProperty(prefix = "clusterj", name = {"connectString", "dataBaseName"})
public class ClusterJAutoConfiguration {

    private final ClusterJProperties clusterJConfigProperties;

    @Autowired
    public ClusterJAutoConfiguration(ClusterJProperties clusterJConfigProperties) {
        this.clusterJConfigProperties = clusterJConfigProperties;
    }

    @Bean
    @ConditionalOnMissingBean
    public SessionFactory sessionFactory() {
        Properties clusterJProperties = new Properties();
        clusterJProperties.setProperty("com.mysql.clusterj.connectstring", clusterJConfigProperties.getConnectString());
        clusterJProperties.setProperty("com.mysql.clusterj.database", clusterJConfigProperties.getDataBaseName());
        clusterJProperties.putAll(clusterJConfigProperties.getProperties());
        return ClusterJHelper.getSessionFactory(clusterJProperties);
    }
}

我想在另一个模块中使用此启动器。为此,我创建了一个组件,并将该bean注入其中:

@Component
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
    }
}

但是,clusterj.connectString中不存在属性clusterj.connectStringapplication.yml时,不会创建bean SessionFactory。可以,但是GetEntityHandler要创建,但会出错:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getEntityHandler' defined in file [GetEntityHandler.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mysql.clusterj.SessionFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

如果上下文中不存在GetEnityNandler bean,如何使我的SessionFactory组件不被创建?

0 个答案:

没有答案