Bean creation exception - java

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.

Related

Did not find bean NoSuchBeanDefinitionException

I try to get bean, by using ClassPathXmlApplicationContext. But I receive: NoSuchBeanDefinitionException: No bean named 'newsController' is defined
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("classpath*:conf/Spring_Config.xml");
NewsController newsController = (NewsController)
applicationContext.getBean("newsController");
In xml:
<bean id="newsController" class="NewsController"/>
Add full path to the bean class tag
class=com.foo.NewsController

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!

How to autowire spring.xml defined beans into #Component Beans

I have a large Spring Project, whose beans are mostly created via the #Component annotation on classes. I'm slowly tring to move the bean definition to the spring.xml config file.
I however, get a the following error whenever I try to autowire a bean created in the xml config file into a bean created via the #Component annotation.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ComponentBean' defined in class path resource [spring.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'xmlBean' of bean class [myproject.XmlBean]: Bean property 'xmlBean' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
In my spring.xml:
<bean id="xmlBean" class="myproject.XmlBean" />
Trying to autowire beans into #Component beans as follows does not work:
#Component
class ComponentBean {
#Autowired
private XmlBean xmlBean;
// Bean setters and getters
}
Is there a way by which I could marsh up the two, as I slowly port my bean definitions to the spring.xml config file.

How to create request scoped web service port?

I have Spring MVC based web application that calls web service. Web service requires http based authentication for every call.I hold web Service Proxy configuration in applicationContext.xml:
<beans...
<bean id="paymentWebService"
class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean">
<property name="customProperties">
<ref local="jaxwsCustomProperties"/>
</property>
<property name="serviceInterface" value="com.azercell.paymentgateway.client.PaymentGatewayWebService"/>
<property name="wsdlDocumentUrl"
value="#{config.wsdlDocumentUrl}"/>
<property name="namespaceUri" value="http://webservice.paymentgateway.azercell.com/"/>
<property name="serviceName" value="PaymentGatewayWebServiceImplService"/>
<property name="portName" value="PaymentGatewayWebServiceImplPort"/>
</bean>
I have instance field for web service port in my controller:
#Controller
public class PaymentController {
#Resource(name = "paymentWebService")
private PaymentGatewayWebService paymentPort;
#ModelAttribute
public void ajaxAttribute(WebRequest request, Model model) {
UtilMethods.authenticationWebServicePort(paymentPort);
...
}
...
#RequestMapping(value = "/massPayment", method = RequestMethod.POST)
public String massPayment(#RequestParam String amount, #RequestParam MultipartFile file, Model model, Locale locale) {
...
WebServiceResponse response = paymentPort.massPayment(UtilMethods.getNewRequestId()
, fileUploader, UtilMethods.getAmountInCoins(amountBigDecimal), null);
...
return SpringView.MASS_PAYMENT.toString(ajaxRequest);
}
}
Code of UtilMethods.authenticationWebServicePort:
public static void authenticationWebServicePort(PaymentGatewayWebService paymentPort) {
String username = (String) RequestContextHolder.currentRequestAttributes().getAttribute(USERNAME_SESSION_VARIABLE_NAME, RequestAttributes.SCOPE_SESSION);
String password = (String) RequestContextHolder.currentRequestAttributes().getAttribute(PASSWORD_SESSION_VARIABLE_NAME, RequestAttributes.SCOPE_SESSION);
BindingProvider prov = (BindingProvider) paymentPort;
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
}
As controllers are singleton objects there occurring problems every time when requests overlap, if to be precisely one user by mistake can use web methods with username and password that belong to another user.
To prevent this I tried to make web service port request scoped in configuration as below:
<bean id="paymentWebService"
class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean" scope="request">
in this case I got error:
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 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#0': Cannot resolve reference to bean 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0' while setting constructor argument with key [2]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0': Cannot resolve reference to bean 'org.springframework.security.authentication.ProviderManager#0' while setting bean property 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.ProviderManager#0': Cannot resolve reference to bean 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager': Cannot resolve reference to bean 'myAuthenticationProvider' while setting constructor argument with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myAuthenticationProvider': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'paymentWebService': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
How to create request scoped web service port?
Try to expose current http request to spring. Just add RequestContextListener in your web.xml:
<web-app>
...
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
...
</web-app>
See this entry from official documentation for more details / options.
EDIT. Think about the difference in lifecycle between controller and paymentPort dependency. Controller is always the same, but paymentPort must be refreshed for each new request. So you cann't continue inject it directly. You need to get fresh instance for each request. You can do it using javax.inject.Provider interface.

Spring bean creation error

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);

Categories