Spring BeanCreationException: cannot resolve reference to bean exception - spring

I am trying the example application at the following web site:
JSF 2, PrimeFaces 3, Spring 3 & Hibernate 4 Integration Project
But I find that when running the project, I get:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserService' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'UserDAO' while setting bean property 'userDAO'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserDAO' defined in ServletContext resource [/WEB-INF/applicationContext.xml]
However, in the applicationContext.xml file, the relevant code is as follows:
<!-- Beans Declaration -->
<bean id="User" class="com.otv.model.User"/>
<!-- User Service Declaration -->
<bean id="UserService" class="com.otv.user.service.UserService">
<property name="userDAO" ref="UserDAO" />
</bean>
<!-- User DAO Declaration -->
<bean id="UserDAO" class="com.otv.user.dao.UserDAO">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
<!-- Session Factory Declaration -->
<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="DataSource" />
<property name="annotatedClasses">
<list>
<value>com.otv.model.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
The classes do exist in the relevant packages as well as can be seen below and the location of the various config files.
The only difference I can see between the tutorial and my implementation of it is that I am using NetBeans 7.2 rather than Eclipse.
Has anyone any idea as to why this is?

/WEB-INF/applicationContext.xml should contain an entry like <bean id="UserDAO" class="com.otv.dao.UserDAO">...</bean> whose properties largely depend on the backend system used.
I also suspect that the User bean is a bad copy and past as User instances should be retrived from the DAO or created programmatically.
As to why it works in Eclipse and not in Netbeans, it is too strange to be true. There must be some clutter...

I found the main cause of that error. It is actually quit simple.
In the class com.otv.model.User, there is no #Id annotation above the field id.
Here is the link for the answer that lead me to find what was the mistake : hibernate exception: org.hibernate.AnnotationException: No identifier specified for entity: com..domain.idea.MAE_MFEView

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserService' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'UserDAO' while setting bean property 'userDAO';
This is telling you that UserService can't be created because its missing a property definition
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserDAO' defined in ServletContext resource [/WEB-INF/applicationContext.xml]
This tells you that the definition for UserDAO can't be found.
You are missing the UserDao definition, the ref just means that it should be of that type, it still needs a bean definition.
Basically, whenever you use "ref" you are telling spring to make a property of that type. That type needs to be defined in its own bean definition.
So if UserDao uses some other property that again is defined by a "ref" that property will need its own bean definition as well.
You have to think of the classes and the spring definitions to be two completely separate entities. The classes might be there and placed where they should, but spring needs its bean definitions in order to invoke them. It doesn't know what a UserDao or SessionFactory is unless you specifically tell it which package/class you want to be invoked.

Related

Add a list of groovy files using <lang:groovy>

I have integrated groovy in my application using spring. My context looks like:
<lang:groovy id="myConfiguration"
script-source="classpath:MyGroovy.groovy"
refresh-check-delay="1000"/>
MyGroovy is an implementation of MyInterface. I was wondering how can I add more files in my classpath (also implementing the same interface) and to have more beans like the one above dynamically?
I would like to get something like:
<lang:groovy id="myConfiguration"
script-source="classpath:*.groovy"
refresh-check-delay="1000"/>
And later be able to use a list of implementations of MyInterface and sent it to another bean where I can go through the list and do stuff. My bean would like like:
<bean id="myProcessor"
class="com.package.processor.MyProcessor">
<constructor-arg>
<list value-type="com.package.processor.MyInterface">
<bean class="MyGroovy1"/>
<bean class="MyGroovy2"/>
<bean class="MyGroovy3"/>
</list>
</constructor-arg>
</bean>
Is this possible at all? I have just changed the first part and I already get Exceptions and haven't found in the documentation anything related to this topic.
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'myProcessor': Could not determine
scripted object type for GroovyScriptFactory: script source locator
[classpath:.groovy]; nested exception is
java.io.FileNotFoundException: class path resource [.groovy] cannot
be opened because it does not exist

Grails - RabbitMQ and listener - too more onMessage call

At first I have application where I'm using RabbitMQ and Grails.
I defined listeners:
<bean id="rabbitListenerCreateDocument" class="org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="queues" ref="rabbitQueuePageInstanceCreated" />
<property name="defaultRequeueRejected" value="false"/>
<property name="messageListener" ref="createPageService" />
<property name="errorHandler" ref="errorHandlerService" />
<property name="transactionManager" ref="mongoTransactionManager"/>
<property name="autoStartup" value="true" />
<property name="concurrentConsumers" value="0" />
</bean>
The problem is that onMessage method from createPageService run too more times.
I think because I got this error (when I turn onlogs from spring):
connection error; reason: com.rabbitmq.client.impl.UnknownChannelException: Unknown channel number 10
After some time I got that spring dosnt send ack to rabbit when this exception was thrown.
Everything should look fine, but...
In'm method onMessage I'm creating document in MongoDB - and I'm geting too much documents - it CRITICAL in my app.
I'm using Mongo to store some objects, and as we all know MongoDB is not transactional.
I think that scenario looks like this:
Listener getting message
method onMessage from createPageService is running
method creating document in Mongo
method onMessage reach to end
Spring want to send ACK to rabbit but it get UnknownChannelException
TransactionManager want to rollback but it can't - there is no transaction on MongoDB
The same message came one more time and now everything works ok (there is no Exception)
I trying to make some modification to solve this but it doesn’t works:
1. First I'm trying to add Around aspect on onMessage method - it dosnt works ... I'm getting:
Error creating bean with name 'grailsApplicationPostProcessor': BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.config.internalTransactionAdvisor': Cannot resolve reference to bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0' while setting bean property 'transactionAttributeSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0': BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.aop.aspectj.AspectJPointcutAdvisor]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: error at ::0 formal unbound in pointcut
I define new transaction manager for connection for bean: createPageService. It not work's too..
Somebody have any idea to solve this problem ?
I've been using this plugin for grails without issues:
https://github.com/pablomolnar/rabbit-ha
It has some extra configuration, but for basics it should be enough.

Defining the same Spring bean twice with same name

Is having two definition for a bean (with same name and class) valid in Spring IOC ?
I am having two bean definition files included in web.xml. See the sample below.
applicationContext-beans1.xml
<bean name="myWao"
class="com.beans.myBean">
</bean>
applicationContext-beans2.xml
<bean name="myWao"
class="com.beans.myBean">
</bean>
I am not facing any issue till now. But, will this possibly impact in the real environment which will be multi threaded and clustered ?
Note: Both the XMLs are loaded as I am able to use the other beans defined(only once) in both the XMLs
It's valid, but you'll find that one bean is overridden by the other. You'll see this in the logs as
Overriding bean definition for...
This behaviour allows you to override previously supplied bean definitions. It affects the static assembly of your app, and doesn't relate to threading/clustering as suggested in your question.
Note that the DefaultListableBeanFactory allows you to configure this behaviour via setAllowBeanDefinitionOverriding()
From Spring Boot version 2.1 it is disabled by default. (link)
Bean Overriding: Bean overriding has been disabled by default to
prevent a bean being accidentally overridden. If you are relying on
overriding, you will need to set
spring.main.allow-bean-definition-overriding to true.
This is valid and useful especially when you try to change the implementation of a third party bean (I mean, where you are not allowed to change the implementation of a bean) and Where you need to provide/configure some extra (merge) properties for the bean.
The overriding of the bean depends upon the order of the xmls you provide to build the ApplicationContext through web.xml or stand-alone. The latest bean definition will win the game.
I know it is very very late to reply, But sill want to add something...
It valid as long as you are defining two bean definitions with same id of same bean on two different spring configuration files. And you are importing one configuration file into another (kind of merging), does not matter how you importing (kind of merging). The later one or the last one bean definition will be override by the first one(s).
package com.demo.bean;
public class TestBean {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
e.g # 1
spring-config1.xml
<bean id="testbean" class="com.demo.TestBean">
<property name="message" value="INSIDE_SPRING_CONFIG_1"></property>
</bean>
spring-config2.xml
<import resource="spring-config1.xml"/><
<bean id="testbean" class="com.demo.TestBean">
<property name="message" value="INSIDE_SPRING_CONFIG_1"></property>
</bean>
e.g # 2
spring-config1.xml
<bean id="testbean" class="com.demo.TestBean">
<property name="message" value="INSIDE_SPRING_CONFIG_1"></property>
</bean>
spring-config1.xml
<bean id="testbean" class="com.demo.TestBean">
<property name="message" value="INSIDE_SPRING_CONFIG_1"></property>
</bean>
web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-config1.xml,
/WEB-INF/spring-config2.xml
</param-value>
</context-param>
But if you are defining the two bean definitions with same bean id of same bean in same file you will find spring application start up failed. Spring would not let you define multiple bean definitions of same bean with same name in the same spring configuration file.
e.g # 3
spring-config3.xml
<bean id="testbean" class="com.demo.TestBean">
<property name="message" value="CONFIG_VALUE_1"></property>
</bean>
<bean id="testbean" class="com.demo.TestBean">
<property name="message" value="CONFIG_VALUE_2"></property>
</bean>
Error :
ERROR ContextLoader:331 - Context initialization failed
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Bean name 'testbean' is already used in this <bean> element
Offending resource: resource [/spring-config3.xml]
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:70)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:316)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.checkNameUniqueness(BeanDefinitionParserDelegate.java:525)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseBeanDefinitionElement(BeanDefinitionParserDelegate.java:471)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseBeanDefinitionElement(BeanDefinitionParserDelegate.java:443)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.processBeanDefinition(DefaultBeanDefinitionDocumentReader.java:314)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:205)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:184)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:141)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:110)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:508)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:391)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:335)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4716)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5178)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:152)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1403)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1393)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

bean class instantiation in spring for a class without default constructor

I am using a third party library class XYZ as an argument in my model. XYZ does not have a default constructor. So spring is not able to create bean for it giving error message as
org.springframework.web.util.NestedServletException: Request processing failed;
nested exception is org.springframework.data.mapping.model.MappingInstantiationException:
Could not instantiate bean class [org.abc.def.XYZ]: No default constructor found;nested exception is java.lang.NoSuchMethodException: org.abc.def.XYZ./<init/>()
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:681)
What can I do to resolve this ? I can't add default constructor to XYZ.
I added the following in my dispatcher servlet, but it still don't works.
<bean name="token" class="org.abs.def.Xyx">
<constructor-arg name="arg1" value="val1"/>
<constructor-arg name="arg2" value="val2"/>
<constructor-arg name="arg3" value="val3"/>
</bean>
Thanks.
You can define it in the XML file as a spring bean passing all necessary parameters to instantiate it.
sample:
<bean id="xyz" class="com.a.b.Xyz" >
<constructor-arg index="0" ref="anotherBean"/>
<constructor-arg index="1" value="12"/>
</bean>
You'll need to provide <constructor-arg> elements in your application context config file, as described in the documentation.

Spring, XML beans call Annotation beans when app start

I have one Annotation bean with some methods. It works fine.
public #Controller("adminController") class AdminController {
...
private #Autowired AdminDAO adminDAO;
public void resetTemporalList() {
System.out.println("HE SIDO EJECUTADO.");
this.adminDAO.resetTemporalRegisters();
}
...
}
Now, I am integrating one quartz task. But I am load it with XML definition beans that call previus annotation bean.
<bean id="resetTemporalRegisters" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="adminController" />
<property name="targetMethod" value="resetTemporalList" />
<property name="concurrent" value="false" />
</bean>
Whan I start my app appear next error.
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'adminController' is defined
I believe the problem is that Spring load XML beans first, after Annotation beans, then in this moment "adminController" bean not exits...
How Can I fix it?
SOLVED IT!!
Problem was in I put xml bean definitions in applicationContext.xml.
No, XML and annotations integrate fine, but do you actually have the component scanning code in your XML?
<context:component-scan base-package="com.yourcompany.yourapp"/>
See: 4.10 Classpath scanning and managed components
A little bit of guessing: your controller is defined in child application context created by Spring MVC while you resetTemporalRegisters job in main application context (parent). Child context can access beans from parent context but not the other way around.
This raises important question: why is your business logic trying to call a method of a controller? These methods should be called only be the MVC framework. Can't you just call
this.adminDAO.resetTemporalRegisters();
directly from your job?
<bean id="resetTemporalRegisters" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="adminDAO" />
<property name="targetMethod" value="resetTemporalRegisters" />
<property name="concurrent" value="false" />
</bean>
adminDAO is probably defined in parent context, so you can access it easily.

Resources