如何解决“没有可用类型的合格Bean:预计至少有1个有资格作为自动装配候选者的Bean

时间:2019-05-28 13:50:34

标签: java spring spring-data-jpa

我正在尝试将Spring Data添加到我的项目中。我创建存储库。但是我在使用@Autowired时遇到问题。我收到错误消息“ NoSuchBeanDefinitionException:没有类型为'myapp.CourseRepository'的合格bean:应该至少有1个可以作为自动装配候选的bean”

我检查了Spring版本(4.3.24.RELEASE)和Spring Data版本(Lovelace-SR8),但是可以。

根本原因 org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“ courseServiceImpl”的bean时出错:通过字段“ courseRepository”表示的不满足的依赖关系;嵌套的异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有类型为“ myapp.CourseRepository”的合格Bean:应该至少有1个有资格作为自动装配候选的Bean

@Repository
public interface CourseRepository extends CrudRepository<Course,Integer>,JpaSpecificationExecutor<Course> {
}

@Service
public interface CourseService {
    List<CourseDTO> getCourses();
}

EDIT!!!
@Configuration
public class AppConfig {
        //private Properties dataSourceProperties;

    @Bean
    @DependsOn("flyway")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[]{"myapp"});

       JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());

        return em;
    }
    @Bean
    public DataSource dataSource(){

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/elearning?characterEncoding=latin1&useConfigs=maxPerformance");
        dataSource.setUsername( "root" );
        dataSource.setPassword( "admin" );
        return dataSource;
    }

    @Bean(initMethod = "migrate")
    Flyway flyway() {
        Flyway flyway = Flyway
                .configure()
                .dataSource(dataSource())
                .baselineOnMigrate(true)
                .load();


        return flyway;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);

        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");

        return properties;
    }
}

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseRepository courseRepository;

    @Transactional
    public void testMethod() {

        List<Course> courseList = (List<Course>) courseRepository.findAll();
    }

It is log
Root Cause
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'courseServiceImpl': Unsatisfied dependency expressed through field 'courseRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'myapp.CourseRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
    org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:364)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1268)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:756)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:171)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    org.apache.tomee.catalina.OpenEJBSecurityListener$RequestCapturer.invoke(OpenEJBSecurityListener.java:97)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:748)

1 个答案:

答案 0 :(得分:0)

阅读此spring文档以了解Spring Data Repositories的正确实现:

https://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html

错误的是:

@Service  
public interface CourseService {
    List<CourseDTO> getCourses();
}

更改为此:

public interface CourseService {
     List<CourseDTO> getCourses();
}

未注释Bean的接口。