java Spring 预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33962099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:20:54  来源:igfitidea点击:

Spring expected at least 1 bean which qualifies as autowire candidate for this dependency

javaspringhibernate

提问by yeaaaahhhh..hamf hamf

I am using Spring and Hibernate and I am trying to "wire" the classes that are necessary in order to Autowirea Repositoryinside a Service.

我使用Spring和Hibernate和我想的是,为了是必要的,“线”类的Autowire一内部服务

The Repository class extends CrudRepository

Repository 类扩展了 CrudRepository

StopRepository

停止存储库

@Repository
@RepositoryRestResource(collectionResourceRel = "stop", path = "stop")
public interface StopRepository extends CrudRepository<StopJPA, Long> {

    StopJPA findById(@Param("id") Long id);

    StopJPA findByIdStop(@Param("idStop") String idStop);

    @Override
    void delete(StopJPA deleted);

    @Override
    List<StopJPA> findAll();

    // Optional<StopJPA> findOne(Long id);
    @Override
    StopJPA findOne(Long id);

    @Override
    StopJPA save(StopJPA persisted);

    void flush();

}

The Entity class.

实体类。

StopJPA

停止JPA

@Entity
@Table(name = "stop")
@EntityListeners(RepoListener.class)
public class StopJPA implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Column(name = "stop_description")
    private String stopDescription;

    @Column(name = "id_stop", nullable = false)
    private String idStop;

    public StopJPA() {
    }

    public StopJPA(String stopDescription, String idStop) {
        this.stopDescription = stopDescription;
        this.idStop = idStop;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getStopDescription() {
        return stopDescription;
    }

    public void setStopDescription(String stopDescription) {
        this.stopDescription = stopDescription;
    }

    public String getIdStop() {
        return idStop;
    }

    public void setIdStop(String idStop) {
        this.idStop = idStop;
    }

}

And the Service class implementation:

和服务类实现:

StopService

停止服务

@Service
final class RepoStopService {

@Service
final class RepoStopService {

    private final StopRepository stopRepository;

    @Autowired
    RepoStopService(StopRepository stopRepository) {
        this.stopRepository = stopRepository;
    } 
}

Unfortunately when i try to run it on server i get this exception:

不幸的是,当我尝试在服务器上运行它时,出现此异常:

SEVERE: Exception sending context initialized event to listener instance of class
org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repoStopService' defined in file ...\RepoStopService.class:
Unsatisfied dependency expressed through constructor argument with index 0 of type [com.project.app.services.repositories.StopRepository]: : No qualifying bean of type
[com.project.app.services.repositories.StopRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {};

nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.project.app.services.repositories.StopRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {} at .....

严重:异常将上下文初始化事件发送到类
org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为“repoStopService”的 bean 时出错,在文件 ...\RepoStopService.class 中定义:
通过构造函数参数表示不满意的依赖项,类型为 [com.project.app.services.repositories.StopRepository]: :没有
找到类型为[com.project.app.services.repositories.StopRepository] ​​的合格 bean依赖项:预期在至少 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{};

嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到类型为 [com.project.app.services.repositories.StopRepository] ​​的合格 bean 依赖项:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{} at .....

Does anyone know why Spring doesnt pick up the @Repositoryannotation?

有谁知道为什么 Spring 不选择@Repository注释?



My Configuration consists in 3 files. An AppInitializerclass that implements WebApplicationInitializer, a WebMvcConfigclass that extends WebMvcConfigurerAdapterand lastly a PersistentContextclass.

我的配置包含 3 个文件。一个AppInitializer类实现WebApplicationInitializer,一个WebMvcConfig扩展类WebMvcConfigurerAdapter和最后一个PersistentContext类。

AppInitializer

应用初始化器

public class AppInitializer implements WebApplicationInitializer {

    private static final String CONFIG_LOCATION = "com.project.app.config";
    private static final String MAPPING_URL = "/";

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        // Create the 'root' Spring application context
        WebApplicationContext context = getContext();

        // Manage the lifecycle of the root application context
        servletContext.addListener(new ContextLoaderListener(context));

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet",
                new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping(MAPPING_URL);

    }

    private AnnotationConfigWebApplicationContext getContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation(CONFIG_LOCATION);
        return context;
    }

WebMvcConfig

WebMvcConfig

@EnableWebMvc
@Configuration
//@EnableJpaRepositories
@ComponentScan(basePackages = { "com.project.app" })

public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private Environment env;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("hello");
    }

    @Bean
    public ApplicationContextProvider applicationContextProvider() {
        return new ApplicationContextProvider();
    }
}

PersistentContext

持久上下文

@Component
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class PersistenceContext {

    @Autowired
    private Environment env;

    @Bean
    @Primary
    public DataSource dataSource() throws ClassNotFoundException {
        DataSource ds = new DataSource();

        String url = env.getProperty(SystemSettings.AMTAB_DS_URL);
        String user = env.getProperty(SystemSettings.AMTAB_DS_USERNAME);
        String pass = env.getProperty(SystemSettings.AMTAB_DS_PASSWORD);
        String driver = env.getProperty(SystemSettings.AMTAB_DS_DRIVER);

        // ds.setDriverClassName("org.postgresql.Driver");
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(user);
        ds.setPassword(pass);

        return ds;
    }

    @Bean
    LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactoryBean.setPackagesToScan("com.project.app.services.entities");

        Properties jpaProperties = new Properties();

        // Configures the used database dialect. This allows Hibernate to create SQL
        // that is optimized for the used database.
        jpaProperties.put("hibernate.dialect",
                env.getRequiredProperty(SystemSettings.HIBERNATE_DIALECT));

        // Specifies the action that is invoked to the database when the Hibernate
        // SessionFactory is created or closed.
        jpaProperties.put("hibernate.hbm2ddl.auto",
                env.getRequiredProperty(SystemSettings.HIBERNATE_HBM2DDL));

        // Configures the naming strategy that is used when Hibernate creates
        // new database objects and schema elements
        // jpaProperties.put("hibernate.ejb.naming_strategy",
        // env.getRequiredProperty(SystemSettings.HIBERNATE_NAMING_STRATEGY));

        // If the value of this property is true, Hibernate writes all SQL
        // statements to the console.
        jpaProperties.put("hibernate.show_sql",
                env.getRequiredProperty(SystemSettings.HIBERNATE_SHOW_SQL));

        // If the value of this property is true, Hibernate will format the SQL
        // that is written to the console.
        jpaProperties.put("hibernate.format_sql",
                env.getRequiredProperty(SystemSettings.HIBERNATE_FORMAT_SQL));

        entityManagerFactoryBean.setJpaProperties(jpaProperties);

        return entityManagerFactoryBean;
    }

    /**
     * Because we are using JPA, we have to create a transaction manager bean that integrates the
     * JPA provider with the Spring transaction mechanism. We can do this by using the
     * JpaTransactionManager class as the transaction manager of our application.
     *
     * We can configure the transaction manager bean by following these steps:
     *
     * -> Create a new JpaTransactionManager object. -> Configure the entity manager factory whose
     * transactions are managed by the created JpaTransactionManager object.
     **/
    @Bean
    JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }

}

SOLUTION

解决方案

I just needed to specify alsothe package of the repositories, because its a location that wont be searched by default --> @EnableJpaRepositories("com.project.app.services.repositories")

我只需要指定存储库的包,因为这不会被默认搜索其位置- > @EnableJpaRepositories(“com.project.app.services.repositories”)

回答by Rafael Naufal

As you are using Spring Data, you have to declare the @ComponentScanand the @EnableJpaRepositoriesannotations on your @Configurationclass.

当您使用Spring Data 时,您必须在类上声明@ComponentScan@EnableJpaRepositories注释@Configuration

About the @EnableJpaRepositoriesjavadoc:

关于@EnableJpaRepositoriesjavadoc

Annotation to enable JPA repositories. Will scan the package of the annotated configuration class for Spring Data repositories by default.

启用 JPA 存储库的注释。默认会扫描 Spring Data 仓库的注解配置类的包。