简体   繁体   中英

Spring Hibernate-JPA using Java Based Configuration org.springframework.beans.factory.NoSuchBeanDefinitionException

Hello guys I am having some troubles while working with spring-JPA and testing the code in main method I would really appreciate it if anybody can tell me what's that I am missing here or can direct me towards a good complete tutorial .

Here is my configuration class

@Configuration
@EnableJpaRepositories
public class Config  {

@Bean
public InsertExample insertExample() {
    return new InsertExample() ; 
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean emfb =   new LocalContainerEntityManagerFactoryBean() ; 
    emfb.setDataSource(dataSource());
    emfb.setPackagesToScan("com.solveit.insert");
    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter() ;
    emfb.setJpaVendorAdapter(vendorAdapter);
    return emfb ; 
}

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/datastore");
    dataSource.setUsername("root");
    dataSource.setPassword("nikolis");
    return dataSource ;
}

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

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

@Bean
public Properties hibernateProperties() {
    Properties hibernateProps = new Properties();
    hibernateProps.setProperty("hibernate.hbm2ddl.auto", "create");
    return hibernateProps;
}
}

This is my repository

 public interface ExampleRepository extends     CrudRepository<ExampleModel, Long> {
 List<ExampleModel> findByLastName(String lastName);
}

This is the model

@Entity 
public class ExampleModel {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;

    @Column
    private String klass ;

    @ElementCollection
    private List<Double> features ;

    public  ExampleModel() {

    }

    public ExampleModel(String klass, ArrayList<Double> features) {
        this.klass=klass ;
        this.features=features ; 
    }

    public String getKlass() {
        return klass;
    }

    public void setKlass(String klass) {
        this.klass = klass;
    }

    public ArrayList<Double> getFeatures() {
        return (ArrayList<Double>) features;
    }

    public void setFeatures(ArrayList<Double> features) {
        this.features = features;
    }

}

And this is my test code :

@Configuration
@Import({ Config.class })
public class InsertExample implements CommandLineRunner {

    @Autowired
    ExampleRepository repository ;

    public static void main(String args[]) throws FileNotFoundException{
         SpringApplication.run(InsertExample.class);
    }

    public void run(String... arg0) throws Exception {
        PrintStream out = new PrintStream(new FileOutputStream("output.txt"));


        ArrayList<Double> asdf = new ArrayList<Double>(); 
        asdf.add(23.123) ; 
        asdf.add(23.123) ; 
        asdf.add(23.123) ; 
        asdf.add(23.123) ; 
        ExampleModel example = new ExampleModel("first", asdf) ; 
        repository.save(example) ; 
    }
}

And this is the Exception that I get

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'insertExample': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.solveit.insert.ExampleRepository com.solveit.insert.InsertExample.repository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.solveit.insert.ExampleRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at com.solveit.insert.InsertExample.main(InsertExample.java:33)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.solveit.insert.ExampleRepository com.solveit.insert.InsertExample.repository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.solveit.insert.ExampleRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 15 more
 Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.solveit.insert.ExampleRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 17 more

You need to use this annotation with the package path:

@EnableJpaRepositories("com.solveit.insert.hereyourrepositories")

UPD : At least, you have to do this after changing path in @EnableJpaRepositories:

1.Spring boot config required this structure. Because spring didn't start scanning of the beans which needs to be initialized like JPA.

http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-structuring-your-code.html

2.You can use only JpaTransactionManager.

PlatformTransactionManager is interface, but JPATransactionManager is implementation of interface that understands JPA.

You should read the chapter Transaction Management from the Spring reference to better understand this topic.

http://docs.spring.io/spring/docs/3.0.4.RELEASE/spring-framework-reference/html/transaction.html

  1. hibernateProps.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");

It needs for working with JPA.

Other changes not important.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM