Spring预计至少有一个bean可以作为此依赖项的autowire候选者

时间:2015-11-27 17:12:54

标签: java spring hibernate

我正在使用Spring和Hibernate,我正在尝试“连接”必要的类,以便在服务中自动 存储库

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();

}

实体类。

StopJPA

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

}

Service类实现:

StopService

@Service
final class RepoStopService {

@Service
final class RepoStopService {

    private final StopRepository stopRepository;

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

不幸的是,当我尝试在服务器上运行它时,我得到了这个例外:

  

SEVERE:将上下文初始化事件发送给侦听器的异常   班级实例   org.springframework.web.context.ContextLoaderListener
  org.springframework.beans.factory.UnsatisfiedDependencyException:   创建文件中定义名为'repoStopService'的bean时出错   ... \ RepoStopService.class:
  通过构造函数参数表示不满意的依赖关系   索引0的类型   [com.project.app.services.repositories.StopRepository] ​​::不   类型为
的bean   找到[com.project.app.services.repositories.StopRepository]   依赖:预计至少有1个bean可以作为autowire   这种依赖的候选人。依赖注释:{};

     

嵌套异常是   org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   合格的bean类型   找到[com.project.app.services.repositories.StopRepository]   依赖:预计至少有1个bean有资格成为autowire   这种依赖的候选人。依赖注释:{} at   .....

有谁知道为什么Spring没有拿起 @Repository 注释?

我的配置包含3个文件。 实现 WebApplicationInitializer AppInitializer 类, 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

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

}

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

2 个答案:

答案 0 :(得分:3)

当您使用Spring Data时,您必须在var allFiles = document.getElementsByClassName('files'); if (allFiles.length > 4) { alert('Please select a file!'); } else { // code to show apply button } 课程中声明@ComponentScan@EnableJpaRepositories注释。

关于@Configuration javadoc

  

启用JPA存储库的注释。默认情况下,将扫描Spring Data存储库的带注释配置类的包。

答案 1 :(得分:0)

如果您在使用存储库类作为自动装配时遇到此错误。 您只需要根据您的存储库类使用以下注释即可。

Mongo 存储库:@EnableMongoRepositories("spring.mongorestapi.repositories")

JPA 存储库:@EnableJPARepositories("spring.jparestapi.repositories")