Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No qualifying bean of type repository found for dependency in Spring Data JPA

I Spent much of my time with this! My bad! I am unable to solve the issue. This is my first spring Data JPA practice with spring MVC. While deploying the .ear file on tomcat I am getting the following error.

Updated Log

 Caused by: org.springframework.beans.factory.BeanCreationException: Could not au
    towire field: com.demo.controller.customerRepository com.demo.controller.HomeCon
    troller.repository; nested exception is org.springframework.beans.factory.NoSuch
    BeanDefinitionException: No qualifying bean of type [com.demo.controller.custome
    rRepository] found for dependency: expected at least 1 bean which qualifies as a
    utowire candidate for this dependency. Dependency annotations: {@org.springframe
    work.beans.factory.annotation.Autowired(required=true)}
            at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanP
    ostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.j
    ava:561)
            at org.springframework.beans.factory.annotation.InjectionMetadata.inject
    (InjectionMetadata.java:88)
            at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanP
    ostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java
    :331)
            ... 68 more
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No q
    ualifying bean of type [com.demo.controller.customerRepository] found for depend
    ency: expected at least 1 bean which qualifies as autowire candidate for this de
    pendency. 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.AutowiredAnnotationBeanP
    ostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.j
    ava:533)
            ... 70 more
    ERROR: org.springframework.web.servlet.DispatcherServlet - Context initializatio
    n failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean wit
    h name 'homeController': Injection of autowired dependencies failed; nested exce
    ption is org.springframework.beans.factory.BeanCreationException: Could not auto
    wire field: com.demo.controller.customerRepository com.demo.controller.HomeContr
    oller.repository; nested exception is org.springframework.beans.factory.NoSuchBe
    anDefinitionException: No qualifying bean of type [com.demo.controller.customerR
    epository] found for dependency: expected at least 1 bean which qualifies as aut
    owire candidate for this dependency. Dependency annotations: {@org.springframewo
    rk.beans.factory.annotation.Autowired(required=true)}
            at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanP
    ostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java
    :334)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBean
    Factory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBean
    Factory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBean
    Factory.createBean(AbstractAutowireCapableBeanFactory.java:476)
            at org.springframework.beans.factory.support.AbstractBeanFactory$1.getOb
    ject(AbstractBeanFactory.java:303)
            at org.springframework.beans.factory.support.DefaultSingletonBeanRegistr
    y.getSingleton(DefaultSingletonBeanRegistry.java:230)
            at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBe
    an(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.finish
    BeanFactoryInitialization(AbstractApplicationContext.java:757)
            at org.springframework.context.support.AbstractApplicationContext.refres
    h(AbstractApplicationContext.java:480)
            at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshW
    ebApplicationContext(FrameworkServlet.java:663)
            at org.springframework.web.servlet.FrameworkServlet.createWebApplication
    Context(FrameworkServlet.java:629)
            at org.springframework.web.servlet.FrameworkServlet.createWebApplication
    Context(FrameworkServlet.java:677)
            at org.springframework.web.servlet.FrameworkServlet.initWebApplicationCo
    ntext(FrameworkServlet.java:548)
            at org.springframework.web.servlet.FrameworkServlet.initServletBean(Fram
    eworkServlet.java:489)
            at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.
    java:136)
            at javax.servlet.GenericServlet.init(GenericServlet.java:158)
            at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.
    java:1231)
            at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.
    java:1144)
            at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:10
    31)
            at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContex
    t.java:4914)
            at org.apache.catalina.core.StandardContext.startInternal(StandardContex
    t.java:5201)
            at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
            at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase
    .java:725)
            at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:70
    1)
            at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)

            at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:945)

            at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:466
    )
            at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1556)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
    java:62)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
    sorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:483)
            at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.j
    ava:300)
            at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultM
    BeanServerInterceptor.java:819)
            at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801
    )
            at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:
    1460)
            at org.apache.catalina.manager.HTMLManagerServlet.upload(HTMLManagerServ
    let.java:289)
            at org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServ
    let.java:210)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
    icationFilterChain.java:291)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
    ilterChain.java:206)
            at org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPrevent
    ionFilter.java:213)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
    icationFilterChain.java:239)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
    ilterChain.java:206)
            at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52
    )
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
    icationFilterChain.java:239)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
    ilterChain.java:206)
            at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCh
    aracterEncodingFilter.java:108)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
    icationFilterChain.java:239)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
    ilterChain.java:206)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperV
    alve.java:219)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextV
    alve.java:106)
            at org.apache.catalina.authenticator.AuthenticatorBase.invoke(Authentica
    torBase.java:614)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.j
    ava:142)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.j
    ava:79)
            at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAcce
    ssLogValve.java:616)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineVal
    ve.java:88)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.jav
    a:518)
            at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp
    11Processor.java:1091)
            at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(
    AbstractProtocol.java:673)
            at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpo
    int.java:2503)
            at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoin
    t.java:2492)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.
    java:1142)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
    .java:617)
            at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskTh
    read.java:61)
            at java.lang.Thread.run(Thread.java:744)
    Caused by: org.springframework.beans.factory.BeanCreationException: Could not au
    towire field: com.demo.controller.customerRepository com.demo.controller.HomeCon
    troller.repository; nested exception is org.springframework.beans.factory.NoSuch
    BeanDefinitionException: No qualifying bean of type [com.demo.controller.custome
    rRepository] found for dependency: expected at least 1 bean which qualifies as a
    utowire candidate for this dependency. Dependency annotations: {@org.springframe
    work.beans.factory.annotation.Autowired(required=true)}
            at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanP
    ostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.j
    ava:561)
            at org.springframework.beans.factory.annotation.InjectionMetadata.inject
    (InjectionMetadata.java:88)
            at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanP
    ostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java
    :331)
            ... 68 more
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No q
    ualifying bean of type [com.demo.controller.customerRepository] found for depend
    ency: expected at least 1 bean which qualifies as autowire candidate for this de
    pendency. 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.AutowiredAnnotationBeanP
    ostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.j
    ava:533)
            ... 70 more
    27-Sep-2015 23:58:18.330 INFO [http-apr-8080-exec-47] org.apache.catalina.startu
    p.HostConfig.deployWAR Deployment of web application archive D:\ApacheTomcat\apa
    che-tomcat-8.0.26\webapps\springTest.war has finished in 6,377 ms

I have created a spring MVC project and trying the Spring Data JPA example. My project structure looks like attached screen shot.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.cignex</groupId>
    <artifactId>demo</artifactId>
    <name>springTest</name>
    <packaging>war</packaging>
    <version>1.0.0-BUILD-SNAPSHOT</version>
    <properties>
        <java-version>1.6</java-version>
        <org.springframework-version>3.1.1.RELEASE</org.springframework-version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <org.slf4j-version>1.6.6</org.slf4j-version>
    </properties>
    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <!-- <version>${org.springframework-version}</version> -->
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                 </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <!-- <version>${org.springframework-version}</version> -->
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <!-- <version>4.1.4.RELEASE</version> -->
        </dependency>



        <!-- Database (H2) -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

        <!-- DataSource (HikariCP) -->
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
        </dependency>

        <!-- JPA Provider (Hibernate) -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>

        <!-- Spring Data JPA -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
        </dependency>

        <!-- AspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <!-- <version>${org.aspectj-version}</version> -->
        </dependency>   

        <!-- Logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <!-- <version>${org.slf4j-version}</version> -->
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <!-- <version>${org.slf4j-version}</version> -->
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <!-- <version>${org.slf4j-version}</version> -->
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <!-- <version>1.2.15</version> -->
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>runtime</scope>
        </dependency>

        <!-- @Inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <!-- <version>1</version> -->
        </dependency>

        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <!-- <version>1.2</version> -->
        </dependency>

        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <!-- <version>4.7</version> -->
            <scope>test</scope>
        </dependency>        
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.spring.platform</groupId>
                <artifactId>platform-bom</artifactId>
                <version>1.1.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Servlet-Context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.demo" />

</beans:beans>

Entity:

package com.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Customer {

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

    protected Customer() {}

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%d, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }

}

Controller:

package com.demo.controller;

import com.demo.model.Customer;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

    @Autowired
    customerRepository repository;

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);


    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);

        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

        String formattedDate = dateFormat.format(date);

        model.addAttribute("serverTime", formattedDate );

         repository.save(new Customer("Jack", "Bauer"));
         repository.save(new Customer("Chloe", "O'Brian"));
         repository.save(new Customer("Kim", "Bauer"));
         repository.save(new Customer("David", "Palmer"));
         repository.save(new Customer("Michelle", "Dessler"));

         for(Customer customer : repository.findAll())
         {
             System.out.println("Log Results ::  "+customer.toString());
         }

        return "myhome";
    }

}

Configuration:

package com.demo.config;

import java.util.Properties;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;


@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory", value = "com.demo.controller")
@EnableTransactionManagement

public class PersistenceContext {


    @Bean(destroyMethod = "close")
    DataSource dataSource() {
    HikariConfig dataSourceConfig = new HikariConfig();
    dataSourceConfig.setDriverClassName("org.h2.Driver");
    dataSourceConfig.setJdbcUrl("jdbc:h2:mem:datajpa");
    dataSourceConfig.setUsername("sa");
    dataSourceConfig.setPassword("");

    return (DataSource) new HikariDataSource(dataSourceConfig);
    }

    @Bean
    LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setDataSource((javax.sql.DataSource) dataSource);
    entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    entityManagerFactoryBean.setPackagesToScan("com.cignex.repo");

    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", "org.hibernate.dialect.H2Dialect");

    //Specifies the action that is invoked to the database when the Hibernate
    //SessionFactory is created or closed.
    jpaProperties.put("hibernate.hbm2ddl.auto", 
            "create-drop"
    );

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

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

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

    entityManagerFactoryBean.setJpaProperties(jpaProperties);

    return entityManagerFactoryBean;
    }

    @Bean
    JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }

}

customerRepository:

package com.demo.controller;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.demo.model.*;
@Repository
interface customerRepository extends CrudRepository<Customer, Long> {


}

Project Structure: enter image description here

Any suggestion where I made mistake and how to resolve the same.

Also this is my first spring data practice project, If I made any mistakes in code OR configurations OR project structure, Please correct me with your valuable suggestions.

like image 611
Vinod Avatar asked Sep 27 '15 18:09

Vinod


1 Answers

You need to declare the customerRepository class as public. Since you haven't specified any modifier, we cannot subclass the repository if the implementation is in a different package.

Spring creates an implementation for the repository at runtime. If spring creates the runtime implementations for repositories in some other package, then spring won't be able to subclass customerRepository. In that case, there won't be an implementation (and a spring bean of type customerRepository) and you won't be able to autowire customerRepository.

like image 154
yaswanth Avatar answered Oct 15 '22 13:10

yaswanth