Announcement Announcement Module
Collapse
No announcement yet.
Dependency injection problem Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Dependency injection problem

    I'm doing an example from the Pro Srping3 book. I am having a problem with what should be a simple dependency injection

    I have the following implementation class for a ContactService data retrival xface:

    Code:
    package com.apress.prospring3.ch10.service.springjpa;
    
    // Implementation of ContactServiceR xface
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import com.apress.prospring3.ch10.domain.Contact;
    import com.apress.prospring3.ch10.service.ContactService;
    import com.apress.prospring3.ch10.repository.ContactRepository;
    import com.google.common.collect.Lists;
    
    @Service("springJpaContactService")
    @Repository
    @Transactional
    public class ContactServiceImpl implements ContactService {
    
    	// Instead of the EntityManager, we just need to inject the ContactRepository xface
    	// into the service class and Spring Data JPA will do all the dirty work for us.
    	@Autowired
    	private ContactRepository contactRepository;
    	
    
    	
    	public List<Contact> findAll() {
    		return Lists.newArrayList(contactRepository.findAll());
    	}
    
    	@Transactional(readOnly=true)
    	public List<Contact> findByFirstName(String firstName) {
    		return contactRepository.findByFirstName(firstName);
    	}
    
        @Transactional(readOnly=true)
    	public List<Contact> findByFirstNameAndLastName(String firstName,
    			String lastName) {
        	return contactRepository.findByFirstNameAndLastName(firstName, lastName);
    	}
    
    }
    The class I am using to test is:

    Code:
    package com.apress.propring3.ch10;
    
    // Testing Program for ContactServiceR xface and ContactServiceRImpl
    
    import java.util.List;
    
    import org.springframework.context.support.GenericXmlApplicationContext;
    
    import com.apress.prospring3.ch10.domain.Contact;
    import com.apress.prospring3.ch10.service.ContactService;
    
    public class SpringJpaSample {
    
    	public static void main(String[] args) {
     
    		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
    		ctx.load("classpath:spring-data-app-context.xml");
    		ctx.refresh();
    		
    		ContactService contactService = ctx.getBean("springJpaContactService", ContactService.class);
    		
    		// Find all contacts
    		List<Contact> contacts = contactService.findAll();
    		listContacts(contacts);
    		
    		// Find all by first name
    		contacts = contactService.findByFirstName("Clarence");
    		listContacts(contacts);
    		
    		// Find all contacts by first and last name
    		contacts = contactService.findByFirstNameAndLastName("Clarence", "Ho");
    		
    	}
    	
    	private static void listContacts(List<Contact> contacts) {
    	
    		System.out.println("");
    		System.out.println("Listing contacts without details:");
    		for (Contact contact: contacts) {
    			System.out.println(contact);
    			System.out.println("");
    		}
    		
    	}
    
    }
    My config file is:

    HTML Code:
    <?xml version="1.0" encoding="UTF-8"?>	
    <beans xsi:schemaLocation="http://www.springframework.org/schema/beans 
    		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
    		http://www.springframework.org/schema/context 
    		http://www.springframework.org/schema/context/spring-context-3.1.xsd 
    		http://www.springframework.org/schema/jdbc 
    		http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd 
    		http://www.springframework.org/schema/data/jpa 
    		http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd 
    		http://www.springframework.org/schema/tx 
    		http://www.springframework.org/schema/tx/spring-tx-3.1.xsd" 
    	xmlns:tx="http://www.springframework.org/schema/tx" 
    	xmlns:jpa="http://www.springframework.org/schema/data/jpa" 
    	xmlns:jdbc="http://www.springframework.org/schema/jdbc" 
    	xmlns:context="http://www.springframework.org/schema/context" 
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    	xmlns="http://www.springframework.org/schema/beans">
    		
    	<!--  Note we added the jpa namespace to this configuration.-->
    
        <!-- Use the H2 database for testing -->
    	<jdbc:embedded-database id="dataSource" type="H2">
    		<jdbc:script location="classpath:schema.sql"/>
    		<jdbc:script location="classpath:test-data.sql"/>
    	</jdbc:embedded-database>		
    	
    	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    		<property name="entityManagerFactory" ref="emf"/>
    	</bean>
    	
    	<tx:annotation-driven transaction-manager="transactionManager" />
    	
    	<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    		<property name="dataSource" ref="dataSource"/>
    		<property name="jpaVendorAdapter">
    			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    		</property>
    		<property name="packagesToScan" value="com.apress.prospring3.ch10.domain"/>
    		<property name="jpaProperties">
    			<props>
    				<prop key="hibernate.dialect">
    					org.hibernate.dialect.H2Dialect
    				</prop>
    				<prop key="hibernate.max_fetch_depth">3</prop>
    				<prop key="hibernate.jdbc.fetch_size">50</prop>
    				<prop key="hibernate.jdbc.batch_size">10</prop>
    				<prop key="hibernate.show_sql">true</prop>
    			</props>
    		</property>
    	</bean>
    	
    	<context:annotation-config/>
    	
    	<context:component-scan base-package="com.apress.prospring3.ch10.service.springjpa" />
     	
     	<!--  The <jap:repositorie tag is used to configure Spring Data JPA's Repository abstraction. We instruct
     	      Spring to scan the package com.apress.prospring3.ch10.repository for repository interfaces and to
     	      pass in the EntityManagerFactory adn transaction manager respectively-->
     	<jpa:repositories base-package="com.apress.prospring3.ch10.repository"
     				      entity-manager-factory-ref="emf"
     				      transaction-manager-ref="transactionManager"/>
     				      
    </beans>
    When I run the main I get the following exceptions:

    Exception in thread "main" org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name 'springJpaContactService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationExce ption: Could not autowire field: private com.apress.prospring3.ch10.repository.ContactRepos itory com.apress.prospring3.ch10.service.springjpa.Conta ctServiceImpl.contactRepository; nested exception is org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name 'contactRepository': FactoryBean threw exception on object creation; nested exception is java.lang.NoSuchMethodError: org.springframework.data.repository.query.parser.P art.getProperty()Lorg/springframework/data/repository/query/parser/Property;
    at org.springframework.beans.factory.annotation.Autow iredAnnotationBeanPostProcessor.postProcessPropert yValues(AutowiredAnnotationBeanPostProcessor.java: 287)
    at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.populateBean(AbstractAu towireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.doCreateBean(AbstractAu towireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.Abstract BeanFactory$1.getObject(AbstractBeanFactory.java:2 94)
    at org.springframework.beans.factory.support.DefaultS ingletonBeanRegistry.getSingleton(DefaultSingleton BeanRegistry.java:225)
    at org.springframework.beans.factory.support.Abstract BeanFactory.doGetBean(AbstractBeanFactory.java:291 )
    at org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultL istableBeanFactory.preInstantiateSingletons(Defaul tListableBeanFactory.java:605)
    at org.springframework.context.support.AbstractApplic ationContext.finishBeanFactoryInitialization(Abstr actApplicationContext.java:913)
    at org.springframework.context.support.AbstractApplic ationContext.refresh(AbstractApplicationContext.ja va:464)
    at com.apress.propring3.ch10.SpringJpaSample.main(Spr ingJpaSample.java:18)
    Caused by: org.springframework.beans.factory.BeanCreationExce ption: Could not autowire field: private com.apress.prospring3.ch10.repository.ContactRepos itory com.apress.prospring3.ch10.service.springjpa.Conta ctServiceImpl.contactRepository; nested exception is org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name 'contactRepository': FactoryBean threw exception on object creation; nested exception is java.lang.NoSuchMethodError: org.springframework.data.repository.query.parser.P art.getProperty()Lorg/springframework/data/repository/query/parser/Property;
    ........

    The @Autowired contactRepository attribute is not being loaded, I'm not sure why. I added setter and getter methods, and even tried adding a constructor with this attribute as an argument, but it didn't help.

    Can someone help me?
    Thank
    Mike

  • #2
    More info on Autowired injection problem

    I should add that the contactRepository bean I am trying to inject which is failing to be created is defined below. I believe this bean should be created by the <jpa:repositories .... /> tag in the XML file

    Code:
    package com.apress.prospring3.ch10.repository;
    
    import java.util.List;
    
    import org.springframework.data.repository.CrudRepository;
    
    import com.apress.prospring3.ch10.domain.Contact;
    
    public interface ContactRepository extends CrudRepository<Contact, Long> {
    
    	public List<Contact> findByFirstName(String firstName);
    	
    	public List<Contact> findByFirstNameAndLastName(String firstName, String lastName);	
    	
    }
    Last edited by MikeT; Dec 21st, 2012, 04:47 PM. Reason: Update with info left out

    Comment


    • #3
      Looks more of a spring-data module specific issue, but it seems mistakenly you're putting @Service as well as @Repository annotation on your ContactServiceImpl implementation. Spring data module is supposed to take care of all the boiler-plate repository code for you just by creating an abstract representation extending their CrudRepository interface. So you don't have to and would essentially not create a repository instance in code.

      Comment


      • #4
        Originally posted by objectamit View Post
        Looks more of a spring-data module specific issue, but it seems mistakenly you're putting @Service as well as @Repository annotation on your ContactServiceImpl implementation. Spring data module is supposed to take care of all the boiler-plate repository code for you just by creating an abstract representation extending their CrudRepository interface. So you don't have to and would essentially not create a repository instance in code.
        Thanks,
        If I remove the @Repository it does not solve the problem. If I also remove the @Service I get the error:

        Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefini tionException: No bean named 'springJpaContactService' is defined

        Mike

        Comment


        • #5
          Ok,

          let me know what errors do you get when you remove the @Repository annotation while keeping the @Service annotation as is there. Just saying that it doesn't solve the problem doesn't help much.

          Comment


          • #6
            More inof

            Originally posted by MikeT View Post
            Thanks,
            If I remove the @Repository it does not solve the problem. If I also remove the @Service I get the error:

            Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefini tionException: No bean named 'springJpaContactService' is defined

            Mike
            I was able to get rid of the exception about not being able to create the contactRepository bean by adding a constructor method to ContactServiceImpl and moving the @Autowired to the constructor. However
            I am now getting the excption;

            Exception in thread "main" java.lang.NoSuchMethodError: org.springframework.core.MethodParameter.getNested ParameterType()Ljava/lang/Class;
            at org.springframework.beans.factory.config.Dependenc yDescriptor.getDependencyType(DependencyDescriptor .java:235)
            at org.springframework.beans.factory.support.DefaultL istableBeanFactory.resolveDependency(DefaultListab leBeanFactory.java:724)
            at org.springframework.beans.factory.support.Construc torResolver.resolveAutowiredArgument(ConstructorRe solver.java:795)
            at org.springframework.beans.factory.support.Construc torResolver.createArgumentArray(ConstructorResolve r.java:723)
            at org.springframework.beans.factory.support.Construc torResolver.autowireConstructor(ConstructorResolve r.java:196)
            at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.autowireConstructor(Abs tractAutowireCapableBeanFactory.java:1035)
            at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBeanInstance(Abst ractAutowireCapableBeanFactory.java:939)
            at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.doCreateBean(AbstractAu towireCapableBeanFactory.java:485)
            at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:456)
            at org.springframework.beans.factory.support.Abstract BeanFactory$1.getObject(AbstractBeanFactory.java:2 94)
            at org.springframework.beans.factory.support.DefaultS ingletonBeanRegistry.getSingleton(DefaultSingleton BeanRegistry.java:225)
            at org.springframework.beans.factory.support.Abstract BeanFactory.doGetBean(AbstractBeanFactory.java:291 )
            at org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:193)
            at org.springframework.beans.factory.support.DefaultL istableBeanFactory.preInstantiateSingletons(Defaul tListableBeanFactory.java:605)
            at org.springframework.context.support.AbstractApplic ationContext.finishBeanFactoryInitialization(Abstr actApplicationContext.java:913)
            at org.springframework.context.support.AbstractApplic ationContext.refresh(AbstractApplicationContext.ja va:464)
            at com.apress.propring3.ch10.SpringJpaSample.main(Spr ingJpaSample.java:18)

            Comment


            • #7
              Looks like, you're not using MAVEN for dependency management. Actually you're getting a NoSuchMethodError which means that you're not using the correct versions of one or more spring JAR(s). Can you also provide those details?

              Comment


              • #8
                Maven management

                Originally posted by objectamit View Post
                Looks like, you're not using MAVEN for dependency management. Actually you're getting a NoSuchMethodError which means that you're not using the correct versions of one or more spring JAR(s). Can you also provide those details?
                I think I am using maven management, at least when I change my POM file it is reflected in the jars loaded and the resulting error messages. I have checked my jars against what the book indicates is required, I have all required jars, plus some extra. However, there may be conflict to here are the jars I am working with:

                JRE System jars:
                resources.jar, rt.jar, jsse.jar, charsets.jar, dnsns.jar, el-api.jar, jsp-api.jar, localedata.jar, mail.jar, mysqlconnector-java.jar, servlet-api.jar, sunjce_provider.jar, tomcat-dbcp.jar

                Maven dependencies: (.jar left off)
                spring-data-commons-core-1.2.2.RELEASE, spring-beans-3.1.3.RELEASE, spring-tx.3.1.3.RELEASE,
                hibernate-envers-3.6.8.Final, hibernate-core-3.6.8.Final, antlr-2.7.6, commons-collections-3.1,
                dom4j-1.6.1, jta-1.1, hibernate-jpa-api-1.0.1.Final, hibernate-commons-annotations-3.2.Final, slf4j-api-1.6.1,
                aspectjrt-1.6.8, guava-10.0.1, jsr305-1.3.9, jcl-over-slf4j-1.6.1, spring-core-3.1.0.RELEASE,
                spring-asm-3.1.0.RELEASE, commons-logging-1.1.1, spring-data-jpa-1.0.1, spring-aspects-3.1.0.RELEASE,
                spring-context-3.1.0.RELEASE, spring-expressions-3.1.0.RELEASE, hibernate-entitymanager-3.6.8.Final,
                cglib-2.2, asm-3.1, javaist-3.12.0.GA, validation-api-1.0.0.GA, hibernate-validator-4.1.0.Final, junit-4.7,
                spring-test-3.1.0.RELEASE, spring-context-support-3.1.0.RELEASE, spring-aop-3.1.0.RELEASE, aopalliance-1.0,
                spring-orm-3.1.0.RELEASE, spring-jdbc-3.1.0.RELEASE, commons-dbcp-1.2.2, commons-pool-1.3, h2-1.3.156,
                log4j-1.2.16, slf4j-1.2.16, joda-time-2.0, joda-time-hibernate-1.3

                Thanks

                Comment


                • #9
                  As you would have seen yourself, you're using 3.1.3 version of some spring JARs and 3.1.0 version of others. make sure you use the same version for all spring jars. The time you took to copy-paste all names here would have been saved if you would have figured that out yourself as I mentioned in my previous reply.

                  Comment


                  • #10
                    Originally posted by objectamit View Post
                    As you would have seen yourself, you're using 3.1.3 version of some spring JARs and 3.1.0 version of others. make sure you use the same version for all spring jars. The time you took to copy-paste all names here would have been saved if you would have figured that out yourself as I mentioned in my previous reply.
                    I noticed that when I listed the jars and corrected it. Had no effect!.

                    Comment


                    • #11
                      That can't be. If you removed @Repository and kept @Service, also changed all spring dependencies to use version 3.1.3 and after making changes in POM, updated the Maven project configuration and verified before running that you're using all 3.1.3 versions of jar(s), there's no reason for it to fail. Something's wrong at your end only.

                      Comment


                      • #12
                        You are correct, while I corrected the jars, I forgot I left the @Repository in. I took it out and it worked! Thank you very much.

                        Mike

                        Comment

                        Working...
                        X