Spring bean creation error - java

So I've been following the Spring documentation, specifically this part,
http://static.springsource.org/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-collaborators on Dependency Injection, but whenever my code runs, I get an error about bean creation.
Here is portion of my code that I tried to base off the ExampleBean example,
public class TimeFeedHandler implements MessageListener {
String msgID = null;
TimeBayeuxService timeBayeuxService;
public void setTimeBayeuxService(TimeBayeuxService timeBayeuxService) {
this.timeBayeuxService = timeBayeuxService;
}
And my Spring XML file looks like this,
<!-- A POJO that implements the JMS message listener -->
<bean id="timeFeedHandler" class="com.example.streaming.time.TimeFeedHandler" >
<property name="timeBayeuxService" ref="timeBayeuxService"> </property>
</bean>
The error I get is,
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'timeFeedHandler' defined in URL....
Any ideas why or what I'm doing wrong?
Edit, here is the TimeBayeuxService bean,
<!-- Time BayeuxServices -->
<bean id="timeBayeuxService" class="com.example.streaming.time.TimeBayeuxService" lazy-init="true">
<constructor-arg><ref bean="common.bayeux" /></constructor-arg>
<property name="timeBean" ref="time.time" />
</bean>
Here is more of the error. The full error log from STS is wayyyyy too long. I feel like I'm not referencing the TimeBayeuxService bean properly but logically I can't seem to see what I'm doing wrong.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'timeFeedHandler' defined in URL [file:/Users/nullpoint/applicationContext.xml]: Cannot resolve reference to bean 'timeBayeuxService' while setting bean property 'timeFeedHandler'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'timeBayeuxService' defined in URL [file:/Users/nullpoint/applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.example.streaming.time.TimeBayeuxService]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
Here is a portion of the TimeBayeuxService class
public class TimeBayeuxService {
private Bayeux bayeux;
private static StreamingTimeLogGatherer logGatherer;
String testMsgTS = "This is a test message from the original service";
public TimeBayeuxService(Bayeux bayeux) extends SomeBayeuxService{
super(bayeux, TimeBayeuxService.class.getName());
this.bayeux = bayeux;
final Bayeux fbayeux = bayeux;
this.logGatherer = logGatherer;
LogServlet.addLogGatherer(logGatherer);
startThread(fbayeux, testMsgTS, true);
}

timeFeedHandler has a dependency on timeBayeuxService. It can't initialize timeBayeuxService due to NullPointerException so spring can't inject the bean.
According to the error message the NullPointerException happened in the constructor of com.example.streaming.time.TimeBayeuxService. How are you creating common.bayeux bean? Please paste the constructor code for TimeBayeuxService class. Is it an interface? Then you should put the implementation class in the bean definition.
The possible places for NPE. Without the complete stack trace I have to guess the following lines of code:
It can happen inside the constructor of the super class.
These 2 methods: LogServlet.addLogGatherer(logGatherer); startThread(fbayeux, testMsgTS, true);

Related

How to pass return value of a bean to other using Spring MVC

I have a spring bean as follows
package com.test;
#Component
public class Sample{
#Value("${url}")
private String url = null;
public String getURL(){
return "test"+url;
}
}
I have another bean in my context.xml file, which consumes url from above bean
<bean id="build" class="com.test.Consumer">
<property name="url" value="#{new com.test.Sample().getPassword()}"/>
</bean>
But it fails with error below:
java.lang.IllegalStateException: Failed to load ApplicationContext
Expression parsing failed; nested exception is java.lang.NullPointerException
Is this correct: value="#{new com.test.Sample().getURL()}" ?
The correct way would be like this:
#{sample.url}
Where sample is the name of the Sample bean (default name is a name of the class with the first letter converted to lower case) and url is the name of the property you want to get from that bean.
You can check this link for more details: https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/expressions.html#expressions-beandef

Instantiating a cxf service causes injection failure for other unrelated service

I am developing a Consumer Service for some Webservice.
The application is already providing Webservices (as a server), but this is the first consumer.
The generation is ok, but I encounter a weird -to me!- problem as soon as I try to instantiate the javax.xml.ws.Service from the constructor of a consumer service : all provider webservices implementor bean become suddenly "undefined" (if I comment the first provider from cxf.xml, the second one is also 'undefined' as well).
Looks like I trigger some unexpected injection that may happen too soon... but I don't understand why, and how to fix it! Any idea is welcome!
The error trace :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someService' defined in class path resource [spring-core-context.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.my.services.impl.com.my.services.impl.SomeServiceImpl]: Constructor threw exception; nested exception is java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someProviderWebService': Cannot resolve reference to bean 'someProviderWebServiceImplementor' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'someProviderWebServiceImplementor' is defined
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:254)
...
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.my.services.impl.com.my.services.impl.SomeServiceImpl: Constructor threw exception; nested exception is java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someProviderWebService': Cannot resolve reference to bean 'someProviderWebServiceImplementor' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'someProviderWebServiceImplementor' is defined
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:115)
...
Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someProviderWebService': Cannot resolve reference to bean 'someProviderWebServiceImplementor' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'someProviderWebServiceImplementor' is defined
at org.apache.cxf.bus.spring.SpringBusFactory.createBus(SpringBusFactory.java:97)
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someProviderWebService': Cannot resolve reference to bean 'someProviderWebServiceImplementor' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'someProviderWebServiceImplementor' is defined
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'someProviderWebServiceImplementor' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:387)
...
(last)
the cxf.xml
<jaxws:endpoint
id="someProviderWebService"
implementor="#someProviderWebServiceImplementor"
address="/services/SomeProviderWebService"/>
<jaxws:endpoint
id="someProviderWebService2"
implementor="#someProviderWebServiceImplementor2"
address="/services/SomeProviderWebService2"/>
<bean id="logInbound" class="org.apache.cxf.interceptor.LoggingInInterceptor" />
<bean id="logOutbound" class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
<cxf:bus>
<cxf:inInterceptors><ref bean="logInbound" /></cxf:inInterceptors>
<cxf:outInterceptors><ref bean="logOutbound" /></cxf:outInterceptors>
<cxf:inFaultInterceptors><ref bean="logInbound" /></cxf:inFaultInterceptors>
<cxf:outFaultInterceptors><ref bean="logOutbound" /></cxf:outFaultInterceptors>
</cxf:bus>
The someServiceImpl:
public SomeServiceImpl() throws MalformedURLException {
SomeConsumerService service= new SomeConsumerService (); // this is the line causing the problem
}
The webService SomeConsumerService :
public class SomeConsumerService extends javax.xml.ws.Service{
public final static URL WSDL_LOCATION;
public final static QName SERVICE = new QName("urn:test.com:anywhere/webservice/T", "SomeService");
static {
URL url = null;
try {
url = new URL("http://some.wsdl");
} catch (MalformedURLException e) {
System.err.println("Ooops! ");
}
WSDL_LOCATION = url;
}
public SomeConsumerService () {
super(WSDL_LOCATION, SERVICE);
}
}
The Context :
<bean name="someService" class="com.my.services.impl.SomeServiceImpl">
</bean>
<bean name="someProviderWebServiceImplementor" class="com.my.services.impl.SomeProviderWebServiceImplementorImpl">
</bean>
A workmate managed to find out the problem : looks like the cxf servlet will create its own context based on cxf.xml (only!) when it is present. If it is not, it will look for its configuration in application Context.
Though, it also it is only true when I create a consumer... thus, I am not sure whether it is more of an unexpected side-effect, or a true feature.
Anyway, the solution that works here is :
rename cxf.xml to another_name_for_cxf.xml
import the renamed file from application-context.xml (or whatever name you gave it)
<import resource="classpath:another_name_for_cxf.xml"/>
And then, the magic will start to operate!

Error in Spring bean injection : leads to a NullPointerException

I am totally new to Spring framework, bean injections etc, and working on a project organized in many sub-projects about it.
In the commons subproject, containing all Entities, DAOs, DS, I have a MyDS class implementing IMyDS and containing its EntityManager and DAO :
#PersistenceContext(unitName="myPersistenceUnit")
private EntityManager entityManager;
#Autowired
#Qualifier("myDAO")
private IMyDAO mainDao;
Then, I am trying to call this class from the Web part of my project, like this:
#Autowired
private IMyDS myDS;
// then I try to call a function of IMyDS, and get an error at this line :
protected ActionForward executeAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ReefPresentationException {
myDS.callFunction(form);
}
But it doesn't work, giving me a NullPointerException. So far I've guessed the bean is not correctly injected, so I tried to add some information in my application-context-spring.xml file :
<bean id="myDS" class="com.my.project.service.IMyDS" />
And I get this error :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myDS' defined in ServletContext resource [/WEB-INF/config/application-context-spring.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.my.project.service.IMyDS]: Specified class is an interface
So I tried instead to declare the class :
<bean id="myDS" class="com.my.project.service.internal.MyDS" />
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myDS' defined in ServletContext resource [/WEB-INF/config/application-context-spring.xml]: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
So I really have no idea of what is wrong right now...
Thanks for your help
The errors says it all. You have defined your interface IMyDS as a bean and Spring can't instantiate the interface.

Cannot integrate JMX with Spring application

I have got a SPRING application. When I run
mvn jetty:run
everything is ok.
I would like to use JMX in my project.
I created another project, I tried tutorial for beginners and I was able to see some changes with jconsole.
Now, I want to use JMX in my real project and I would like to use SPRING libraries which manages JMX - following this post
How to integrate JMX with Spring?
I have got a class:
public class MyMainClass {
private int var1;
private int var2;
private TimeUnit var3;
// public getters and setters
public static MyXXXClass<String, Object> getInstance();
}
and in config.xml
<!-- other beans -->
<bean id="myid" class="com.my.package.MyMainClass">
<property name="var1" value.../>
<property name="var2" value... />
<property name="var3" value.../>
</bean>
<!-- other beans -->
I changed few things to make it works with JMX.
I added an interface:
import java.util.concurrent.TimeUnit;
public interface IMyMainClassBean {
public int getVar1();
public void setVar1(int var1);
public int getVar2();
public void setVar2(int var2);
public TimeUnit getVar3();
public void setVar3(TimeUnit var3);
}
I added implements to my class:
public class MyMainClassBean implements IMyMainClassBean {...}
Last thing, I edited my xml file:
<!-- other beans -->
<bean id="myid" class="com.my.package.MyMainClassBean">
<property name="var1" value.../>
<property name="var2" value... />
<property name="var3" value.../>
</bean>
<!-- this bean must not be lazily initialized if the exporting is to happen -->
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter"
lazy-init="false">
<property name="beans">
<map>
<entry key="bean:name=testBean1" value-ref="myid" />
</map>
</property>
</bean>
<!-- other beans -->
Now, when I start my server, it gives me a lot of exceptions (log is really long, so I copied just a part which I think is the most important).
Caused by: org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [com.my.package
.MyMainClassBean#3d4395fb] with key 'bean:name=testBean1'; nested exception is javax.management.InstanceAlreadyExistsExcep
tion: bean:name=testBean1
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:602)
at org.springframework.jmx.export.MBeanExporter.registerBeans(MBeanExporter.java:527)
at org.springframework.jmx.export.MBeanExporter.afterPropertiesSet(MBeanExporter.java:413)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableB
eanFactory.java:1571)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBean
Factory.java:1509)
... 163 more
Caused by: javax.management.InstanceAlreadyExistsException: bean:name=testBean1
at com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:453)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.internal_addObject(DefaultMBeanServerInterceptor.java:1484)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:963)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:917)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:312)
at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:483)
at org.springframework.jmx.support.MBeanRegistrationSupport.doRegister(MBeanRegistrationSupport.java:195)
at org.springframework.jmx.export.MBeanExporter.registerBeanInstance(MBeanExporter.java:655)
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:592)
... 167 more
[WARNING] Nested in org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myTask' defined
in class path resource [anotherconfigfile.xml]: Cannot resolve reference to bean 'anotherimport' while setting bean property 'targetObj
ect'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'anotherimport' defin
ed in class path resource [anotherconfigfile.xml]: Cannot create inner bean 'myTotallyAnotherClass' of type [com.my.package.another.MyTotallyAnotherClass]
while setting bean property 'myTotallyAnotherClass'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creatin
g bean with name 'myTotallyAnotherClass' defined in class path resource [anotherconfigfile.xml]: Instantiation of bean failed; nested exception is
org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.my.package.another.MyTotallyAnotherClass]: Co
nstructor threw exception; nested exception is java.lang.ExceptionInInitializerError:
javax.management.InstanceAlreadyExistsException: bean:name=testBean1
at com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:453)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.internal_addObject(DefaultMBeanServerInterceptor.java:1484)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:963)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:917)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:312)
at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:483)
at org.springframework.jmx.support.MBeanRegistrationSupport.doRegister(MBeanRegistrationSupport.java:195)
at org.springframework.jmx.export.MBeanExporter.registerBeanInstance(MBeanExporter.java:655)
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:592)
at org.springframework.jmx.export.MBeanExporter.registerBeans(MBeanExporter.java:527)
at org.springframework.jmx.export.MBeanExporter.afterPropertiesSet(MBeanExporter.java:413)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableB
eanFactory.java:1571)
I have no even idea how to debug it.
Thank you for all your hints.
Caused by: javax.management.InstanceAlreadyExistsException: bean:name=testBean1
This is trying to tell you that you have 2 beans with the same name ObjectName of bean:name=testBean1 being register with the MBeanExporter. However, unless there are other XML files or more entries in your beans map then there should not be.
I have no even idea how to debug it.
You could put a breakpoint in the JmxMBeanServer.registerMBean(...) method to see what beans are being registered to see if you can figure out why you are getting a duplicate.
As an aside, my SimpleJMX library is an easy way to export your beans via JMX. There is pretty good Spring support as well. Here are the documentation about using with Spring. There is also a Spring test program which demonstrates what you need to do to get it working. Here's the Spring XML file.
This is happening as the bean is trying to initialize even after its initialized once.
I was facing the same issue with RabbitMQ configuration in Spring TestNG testcases.
Use #DirtiesContext as a class level annotation for every testcase class.
This will create applicationcontext and kill it once the testcase class is run and a new applicationcontext will be created for the next testcase class.
Example -
#Test
#ContextConfiguration(classes = { ApplicationConfig.class })
#DirtiesContext
#WebAppConfiguration
public class ATest extends AbstractTestNGSpringContextTests{
#BeforeSuite
public void setup() throws Throwable {
}
#AfterSuite
public void teardown() {
}
}

Bean creation exception

My application context looks likt this,
<bean id="caseTxBo" class="gov.case.rcp.bo.impl.caseTxBoImpl" >
<property name="caseTxDao" ref="caseTxDao" />
</bean>
<bean id="caseTxDao" class="gov.case.rcp.dao.impl.caseTxDaoImpl" >
<property name="sessionFactory" ref="sessionFactory" />
Action class gets the context like this:
ServletContext context = request.getSession().getServletContext();
BeanFactory factory = WebApplicationContextUtils.
getRequiredWebApplicationContext(context);
CaseTxBOImpl caseTxBo = (
caseTxBoImpl) factory.getBean("caseTxBo");
List<caseTxPmt> errorVarList =
caseTxBo.getcaseTxDao().findAllcaseTx();
model.put("caseTxList", caseTxList);
BOImpl implements Dao and DAOImpl implements Dao:
DaoImpl has the implementation and returns caseTxList.
but I get a runTimeException as
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'caseTxBo' defined in ServletContext resource [/WEB-INF/classes/applicationContext.xml]: Cannot resolve reference to bean 'caseTxDao' while setting bean property 'caseTxDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'caseTxDao' defined in ServletContext resource [/WEB-INF/classes/applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'sessionFactory' of bean class [gov.case.rcp.pp.dao.impl.CaseTxDaoImpl]: Bean property 'sessionFactory' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
follows:
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104)
Where did i go wrong?
Bean property 'sessionFactory' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
follows:
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
The error message is pretty clear. Open your CaseTxDaoImpl and make sure there is a following method there:
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
BTW this:
ServletContext context = request.getSession().getServletContext();
BeanFactory factory = WebApplicationContextUtils.
getRequiredWebApplicationContext(context);
factory.getBean("caseTxBo")
is pretty low-level usage of Spring and an anti-pattern. Are you using any web framework? Typically they integrate with Spring quite well.

Categories