为什么@Qualifier注释在spring boot 1.5.2中不起作用,但在spring boot 1.2.7中工作

时间:2018-01-15 01:54:14

标签: java spring-boot

在我的项目中,我使用@Qualifier来获取具有相同类的bean对象。 在spring boot 1.2.7代码:

在课堂上a:

@Component
public class DeamonTaskJob implements Job {

    @Autowired
    private QuartzTriggerService quartzTriggerService;

    @Autowired
    private QuartzService quartzService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

    }

    @Bean(name = "deamonJob")
    public JobDetailFactoryBean deamonJob() throws Exception{
        return QuartzConfig.createJobDetail(this.getClass(),TRIGGER_JOB);
    }

    @Bean(name = "deamon")
    public CronTriggerFactoryBean deamonJobTrigger(@Qualifier("deamonJob") JobDetail jobDetail) throws Exception {
        return QuartzConfig.createCronTrigger(jobDetail,TRIGGER_JOB);
    }
}

在班级b:

@Component
public class TestTaskJob implements Job {

    @Autowired
    private TestTaskService testTaskService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("test job start");
        Boolean isSuccess = testTaskService.testService();
        logger.info("test job start");
    }

    @Bean(name = "testJob")
    public JobDetailFactoryBean deamonJob() throws Exception{
        return QuartzConfig.createJobDetail(this.getClass(),TRIGGER_JOB);
    }

    @Bean(name = "test")
    public CronTriggerFactoryBean deamonJobTrigger(@Qualifier("testJob") JobDetail jobDetail) throws Exception {
        return QuartzConfig.createCronTrigger(jobDetail,TRIGGER_JOB);
    }
}

效果很好。

但我将这些代码合并到spring boot 1.5.2,它不起作用。错误是:

No qualifying bean of type [org.quartz.JobDetail] found for dependency [org.quartz.JobDetail]: 
expected at least 1 bean which qualifies as autowire candidate for this dependency. 
Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(val‌​ue=testJob)}

当我在a类中评论代码@Bean(name = "deamonJob")时,它运作良好。

然后我恢复代码并在类b中为testJob方法添加注释@Primary,它可以工作。当我像下面一样添加新的bean时,它会再次出现同样的错误。

然后我使用另一种方法来使用带有ApplicationContext注释的bean,代码如下:

@Bean(name = "testJob")
@Primary
public JobDetailFactoryBean testJob() throws Exception{
    return QuartzConfig.createJobDetail(this.getClass(),TRIGGER_JOB);
}

@Bean(name = "test")
public CronTriggerFactoryBean testTrigger() throws Exception {
    JobDetail integralBlackListJobDetail = (JobDetail)appContext.getAutowireCapableBeanFactory().getBean("testJob");
    return QuartzConfig.createCronTrigger(jobDetail,TRIGGER_JOB);
}

效果很好。

有人可以告诉我为什么吗?谢谢。

0 个答案:

没有答案