Page 1 of 2 12 LastLast
Results 1 to 10 of 13

Thread: @Autowired issue

  1. #1
    Join Date
    Jan 2010
    Posts
    15

    Default @Autowired issue

    Hi All,

    I am facing an issue with 'Autowired' annotation.

    Here is service class:

    @Repository
    @Transactional(readOnly = true)
    public class VisitorDaoImpl implements VisitorDao {

    @Autowired
    public VisitorRepository visitorRepository;

    public void add(Visitor visitor) {
    visitorRepository.save(visitor);
    }

    public void update(Visitor visitor) {
    // TODO Auto-generated method stub
    }

    public void delete(Visitor visitor) {
    // TODO Auto-generated method stub
    }
    }

    And there is my context file:

    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:cloud="http://schema.cloudfoundry.org/spring"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns="http://www.springframework.org/schema/p"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schem...-beans-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schem...ing-tx-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schem...ng-aop-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schem...ontext-3.0.xsd
    http://schema.cloudfoundry.org/spring
    http://schema.cloudfoundry.org/sprin...spring-0.6.xsd
    http://www.springframework.org/schema/data/jpa
    http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <cloud:data-source id="XXXXX"/>
    <context:annotation-config/>
    <bean class="org.springframework.beans.factory.annotatio n.AutowiredAnnotationBeanPostProcessor"/>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <jpa:repositories base-package="com.ehconsulting.sources.dao.repositories "/>


    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerE ntityManagerFactoryBean">
    <property name="persistenceUnitName" value="example"/>
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaVendorAdapter">
    <bean class="org.springframework.orm.jpa.vendor.EclipseL inkJpaVendorAdapter">
    <property name="databasePlatform" value="org.eclipse.persistence.platform.database.M ySQLPlatform" />
    <property name="generateDdl" value="false" />
    <property name="showSql" value="true" />
    </bean>
    </property>
    <property name="loadTimeWeaver">
    <bean class="org.springframework.instrument.classloading .SimpleLoadTimeWeaver"/>
    </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionM anager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
    <property name="dataSource" ref="dataSource"/>
    </bean>

    </beans>

    I always get the following exception:

    org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name 'visitorDaoImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationExce ption: Could not autowire field: public com.ehconsulting.sources.dao.repositories.VisitorR epository com.ehconsulting.sources.dao.impl.VisitorDaoImpl.v isitorRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefini tionException: No matching bean of type [com.ehconsulting.sources.dao.repositories.VisitorR epository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Aut owired(required=true)}
    org.springframework.beans.factory.annotation.Autow iredAnnotationBeanPostProcessor.postProcessPropert yValues(AutowiredAnnotationBeanPostProcessor.java: 286)
    org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.populateBean(AbstractAu towireCapableBeanFactory.java:1074)
    org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.doCreateBean(AbstractAu towireCapableBeanFactory.java:517)
    org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:456)
    org.springframework.beans.factory.support.Abstract BeanFactory$1.getObject(AbstractBeanFactory.java:2 91)
    org.springframework.beans.factory.support.DefaultS ingletonBeanRegistry.getSingleton(DefaultSingleton BeanRegistry.java:222)
    org.springframework.beans.factory.support.Abstract BeanFactory.doGetBean(AbstractBeanFactory.java:288 )
    org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:190)
    org.springframework.beans.factory.support.DefaultL istableBeanFactory.preInstantiateSingletons(Defaul tListableBeanFactory.java:580)
    org.springframework.context.support.AbstractApplic ationContext.finishBeanFactoryInitialization(Abstr actApplicationContext.java:895)
    org.springframework.context.support.AbstractApplic ationContext.refresh(AbstractApplicationContext.ja va:425)
    org.springframework.web.servlet.FrameworkServlet.c reateWebApplicationContext(FrameworkServlet.java:4 42)
    org.springframework.web.servlet.FrameworkServlet.c reateWebApplicationContext(FrameworkServlet.java:4 58)
    org.springframework.web.servlet.FrameworkServlet.i nitWebApplicationContext(FrameworkServlet.java:339 )
    org.springframework.web.servlet.FrameworkServlet.i nitServletBean(FrameworkServlet.java:306)
    org.springframework.web.servlet.HttpServletBean.in it(HttpServletBean.java:127)
    javax.servlet.GenericServlet.init(GenericServlet.j ava:212)
    org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.servic e(CoyoteAdapter.java:298)
    org.apache.coyote.http11.Http11Processor.process(H ttp11Processor.java:859)
    org.apache.coyote.http11.Http11Protocol$Http11Conn ectionHandler.process(Http11Protocol.java:588)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run( JIoEndpoint.java:489)
    java.lang.Thread.run(Thread.java:662)

    May someone help me ?

    Regards.

  2. #2
    Join Date
    Sep 2009
    Location
    Vilnius, Lithuania
    Posts
    118

    Default

    Well the highlighted part of stack trace nails it down quite clearly - no bean of type VisitorRepository can be found. So either it is not there (in the specified package) or something else is wrong with your configuration.
    A few things look suspicious from the first glance:
    1. Why is there an explicit AutowiredAnnotationBeanPostProcessor bean when you also use <context:annotation-config/> (which already registers all common BeanPostProcessors)?
    2. Why is your DAO set up for read-only transactions, and DML methods do not override this setting? Methods like add(), update() and delete() should clearly be readOnly=false.
    3. What good is your DAO when all it does is delegate to Spring Data JPA repository?

  3. #3
    Join Date
    Jan 2010
    Posts
    15

    Default

    Hi Osvaldas,

    Thank you for your reply ! I am new in Spring.

    I removed the <context:annotation-config/>, read-only transactions.

    But I still have the same issue !

    Regards.

  4. #4
    Join Date
    Sep 2009
    Location
    Vilnius, Lithuania
    Posts
    118

    Default

    At this point, I can only guess.
    If you're showing the whole stack trace and there is no hidden root cause, the only possible problem is that for some reason VisitorRepository is not getting declared as a Spring bean.
    Try replacing it with a concrete Repository implementation instead of a Spring Data JPA one, and use an embedded database instead of cloud data-source. Starting from a simple setup might help diagnose the cause.
    Last edited by Osvaldas Grigas; Oct 3rd, 2011 at 05:34 PM.

  5. #5
    Join Date
    Dec 2009
    Location
    India
    Posts
    108

    Default Annotation not correctly placed

    Hi,

    Looking at your problem, I figured out that actually you're using your VisitorDaoImpl as a Service and not as a repository. The repo instance is to be injected automatically as dependency. It means the class which implements VisitorRepository is actually used as a repository and therefore the @Repository annotation should be present on that implementing class and not this one. You're better off using @Service or the generic @Component annotation in this class. Just do two things, Remove Repository annotation from VisitorDaoImpl class and put in @Service or @Component. Make sure that you've annotated your VisitorRepository implementation class with Repository annotation and the package of this class is where spring should scan for components.

  6. #6
    Join Date
    Jan 2010
    Posts
    15

    Default EntityManagerFactory Issue

    Hi Guys,

    I tried all but the issue remains. I changed my configuration like this:

    <cloud:data-source id="XXXXX" />
    <bean class="org.springframework.dao.annotation.Persiste nceExceptionTranslationPostProcessor" />
    <bean class="org.springframework.orm.jpa.support.Persist enceAnnotationBeanPostProcessor" />

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerE ntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
    <bean class="org.springframework.orm.jpa.vendor.Hibernat eJpaVendorAdapter" />
    </property>
    </bean>

    <!-- Add Transaction support -->
    <bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionM anager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <!-- Use @Transaction annotations for managing transactions -->
    <tx:annotation-driven transaction-manager="myTxManager" />


    here is the dao implementation:

    @Component("visitorDao")
    public class VisitorDaoImpl implements VisitorDao {

    @PersistenceContext
    private EntityManager em;

    public void setEm(EntityManager em) {
    this.em = em;
    }

    @Transactional
    public void add(Visitor visitor) {
    em.persist(visitor);
    }
    }

    Here is the stack trace:

    INFO : org.springframework.beans.factory.support.DefaultL istableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultL istableBeanFactory@45c81ac0: defining beans [beanNameViewResolver,cancelForm]; parent: org.springframework.beans.factory.support.DefaultL istableBeanFactory@4e8deb8a
    ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failed
    org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name 'visitorDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefini tionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0
    at org.springframework.orm.jpa.support.PersistenceAnn otationBeanPostProcessor.postProcessPropertyValues (PersistenceAnnotationBeanPostProcessor.java:341)
    at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.populateBean(AbstractAu towireCapableBeanFactory.java:1074)
    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 93)
    at org.springframework.beans.factory.support.DefaultS ingletonBeanRegistry.getSingleton(DefaultSingleton BeanRegistry.java:222)
    at org.springframework.beans.factory.support.Abstract BeanFactory.doGetBean(AbstractBeanFactory.java:290 )
    at org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:192)
    at org.springframework.beans.factory.support.DefaultL istableBeanFactory.preInstantiateSingletons(Defaul tListableBeanFactory.java:585)
    at org.springframework.context.support.AbstractApplic ationContext.finishBeanFactoryInitialization(Abstr actApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplic ationContext.refresh(AbstractApplicationContext.ja va:425)
    at org.springframework.web.servlet.FrameworkServlet.c reateWebApplicationContext(FrameworkServlet.java:4 67)
    at org.springframework.web.servlet.FrameworkServlet.c reateWebApplicationContext(FrameworkServlet.java:4 83)
    at org.springframework.web.servlet.FrameworkServlet.i nitWebApplicationContext(FrameworkServlet.java:358 )
    at org.springframework.web.servlet.FrameworkServlet.i nitServletBean(FrameworkServlet.java:325)
    at org.springframework.web.servlet.HttpServletBean.in it(HttpServletBean.java:127)
    at javax.servlet.GenericServlet.init(GenericServlet.j ava:212)
    at org.apache.catalina.core.StandardWrapper.loadServl et(StandardWrapper.java:1173)
    at org.apache.catalina.core.StandardWrapper.load(Stan dardWrapper.java:993)
    at org.apache.catalina.core.StandardContext.loadOnSta rtup(StandardContext.java:4420)
    at org.apache.catalina.core.StandardContext.start(Sta ndardContext.java:4733)
    at org.apache.catalina.core.ContainerBase.addChildInt ernal(ContainerBase.java:799)
    at org.apache.catalina.core.ContainerBase.addChild(Co ntainerBase.java:779)
    at org.apache.catalina.core.StandardHost.addChild(Sta ndardHost.java:601)
    at org.apache.catalina.startup.HostConfig.deployDirec tory(HostConfig.java:1079)
    at org.apache.catalina.startup.HostConfig.deployDirec tories(HostConfig.java:1002)
    at org.apache.catalina.startup.HostConfig.deployApps( HostConfig.java:506)
    at org.apache.catalina.startup.HostConfig.start(HostC onfig.java:1315)
    at org.apache.catalina.startup.HostConfig.lifecycleEv ent(HostConfig.java:324)
    at org.apache.catalina.util.LifecycleSupport.fireLife cycleEvent(LifecycleSupport.java:142)
    at org.apache.catalina.core.ContainerBase.start(Conta inerBase.java:1061)
    at org.apache.catalina.core.StandardHost.start(Standa rdHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(Conta inerBase.java:1053)
    at org.apache.catalina.core.StandardEngine.start(Stan dardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(Sta ndardService.java:525)
    at org.apache.catalina.core.StandardServer.start(Stan dardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalin a.java:595)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Native MethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(De legatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootst rap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstr ap.java:414)
    Caused by: org.springframework.beans.factory.NoSuchBeanDefini tionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0


    Would you please help ?

    Regards

  7. #7
    Join Date
    Dec 2009
    Location
    India
    Posts
    108

    Default Problem with Application Context Configuration

    Hi,

    Looking at the stack trace it seems that your XML Configuration file where you define datasource, transaction manager is not being read. Therefore the context is not able to detect any beans that you're creating in your XML. How're you loading your XML configuration? I means what is the name of file and how you are initializing spring. those details need to be provided as well.

  8. #8
    Join Date
    Jan 2010
    Posts
    15

    Default EntityManagerFactory Issue

    I previously got visitorDao bean from my application context by doing this: ((VisitorDao)Utility.daoProvider("visitorDao")).ad d(this);. But now I expressly put the context into my web.xml and I still get the same issue.

    Regards

  9. #9
    Join Date
    Jan 2009
    Location
    Huntington Beach, CA
    Posts
    718

    Default

    lallft, what documentation/book/tutorial are you using to learn Spring. Just based on your questions, there are a couple of fundamentals of Spring that you aren't quite grasping yet. So I am going to try to help

    1) Spring's ApplicationContext or container is just a Plain Java object that does some up front work for you based on your xml files that you tell it about. In the end it will have a Map of your objects that were listed in the xml files.

    2) The xml files tells Spring what classes to instantiate for you as well as the dependencies between the classes.

    3) When you use Annotations, exactly like you are currently using, you need to tell Spring that you are using Annotations, otherwise Spring will not include the classes that act on those annotations being there.

    4) Spring parses the xml and when told to scan for Annotations, then it will store all that information to figure out what to instantiate and inject dependencies.

    5) Then it will instantiate that for you.

    6) When that is all done it is ready to go.

    7) If you forget to put a class in your xml, or to Annotate it, then Spring will not know about it to instantiate for you.

    You have <tx:annotation-config/> Which tells Spring to include the class that looks for and acts on @Transactional.

    However, you do not have in your xml the tag to tell Spring that you are using @Component and @Autowired. You do this with <context:component-scan base-package=""/> where you put in the base package to scan for those annotations.

    With @Autowired it is by default a required dependency and Spring will look at the beans/classes that it instantiated for you and inject it. However, if it doesn't find a bean or it finds more than one of that type, then an exception will be thrown, exactly like the exceptions you have posted.

    On top of that you are also trying to learn Spring Data, which I suggest holding off on till you understand the basic Spring concepts and how Spring works at its core.

    Good Luck

    Mark

  10. #10
    Join Date
    Jan 2010
    Posts
    15

    Default EntityManagerFactory Issue

    Hi Mark,

    I made a mistake during my copy/paste. I deleted the context statement. Here is my spring context file:

    <cloud:data-source id="dataSource" />
    <bean class="org.springframework.dao.annotation.Persiste nceExceptionTranslationPostProcessor" />
    <bean class="org.springframework.orm.jpa.support.Persist enceAnnotationBeanPostProcessor" />

    <!-- Use @Component annotations for bean definitions -->
    <context:component-scan base-package="com.sources.dao.impl" />

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerE ntityManagerFactoryBean">
    <property name="persistenceUnitName" value="adelaideweb"/>
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
    <bean class="org.springframework.orm.jpa.vendor.Hibernat eJpaVendorAdapter" />
    </property>
    </bean>

    <!-- Add Transaction support -->
    <bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionM anager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <!-- Use @Transaction annotations for managing transactions -->
    <tx:annotation-driven transaction-manager="myTxManager" />

    By the way, thanks for your advises.

    Regards

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •