Spring NotWritablePropertyException and Invalid property 'lazyInit' of bean JndiObjectFactoryBean - spring

We are using WAS8.5 based JNDI data source configuration. While server start up, this datasource is not getting created. Hence throwing
org.springframework.beans.factory.BeanCreationException by saying "Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'lazyInit' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'lazyInit' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?"
We are not trying to set lazyInit property in our application. What could be the issue here? Is anything missed here?
Spring-context.xml:
<beans
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans">
<context:annotation-config/>
<jee:jndi-lookup id="ds_app1" jndi-name="java:comp/env/jdbc/ds_app1" />
<!-- SQL Session factories -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property ref="ds_app1" name="dataSource"/>
<property name="configLocation" value="classpath:/conf/xml/mybatis-config.xml" />
<property name="mapperLocations" value="classpath:/conf/xml/mapper/*.xml"/>
</bean>
</beans>
Same piece of code is working in another environment with same WAS8.5 server with same set of data source configurations. In our application, we are using spring4.3.8,mybatis3.x and java8. Here we are injecting datasource beans using xml configuration(dao-spring-context.xml)
Expected output would be data source should be injected to sql session factory bean.but actual result is getting the below exception.
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sqlSessionFactory' defined in class path resource [conf/xml/dao-spring-context.xml]: Cannot resolve reference to bean 'ds_app1' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ds_app1': Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'lazyInit' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'lazyInit' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the getter?

This approach worked for me
1) Create a post processor
package org.test;
import org.springframework.bean.PropertyValue;
import org.springframework.bean.PropertyValues;
import org.springframework.bean.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import java.beans.PropertyDescriptor;
#Component
public class CustomJndiInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {
#Override
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
if (bean instanceOf org.springframeworkf.jndi.JndiObjectFactoryBean) {
for (PropertyValue pv: pvs.getPropertyValues()) {
if ("lazyInit".equals(pv.getName())) {
pv.setOptional(true);
}
}
}
}
}
2) Include this bean in your spring context xml
<bean id="customJndiInstantiationAwareBeanPostProcessor" class="org.test.CustomJndiInstantiationAwareBeanPostProcessor"/>

Related

I would like to get advice on Spring BeanCreationException Error

This is the person who asked the question just before.
The error on the question was successful, but I was faced with another error.
As a beginner in Spring, there are many things I don't know and
I have a lot of questions to ask. Please understand.
The error code.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'memberService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private dao.IMemberDAO service.MemberService.memberDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [dao.IMemberDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'memberDao' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'sqlSessionFactory' while setting bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [C:\Users\admin\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\rachelivf\WEB-INF\classes\dao\mapper\memberDaoMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'member'. Cause: java.lang.ClassNotFoundException: Cannot find class: member
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
The following is the MemberService.java code.
package service;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import dao.IMemberDAO;
import model.Member;
#Service
public class MemberService
{
#Autowired
private IMemberDAO memberDao;
public void joinMember(HashMap<String, Object> params)
{
if(params.get("pw").equals(params.get("pwd_CHECK")))
{
memberDao.insertMember(params);
}
}
}
Here is the applicationContext.xml code.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:component-scan base-package="service" />
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property value="com.mysql.jdbc.Driver" name="driverClassName"></property>
<property value="jdbc:mysql://localhost/rachelvf" name="url"></property>
<property value="root" name="username"/>
<property value="mysql" name="password"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath*:dao/mapper/*.xml"></property>
</bean>
<bean id="memberDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
<property name="mapperInterface" value="dao.IMemberDAO"></property>
</bean>
</beans>
As far as I know,
this is the reason why the above error occurs because
I didn't insert the annotation service.
But obviously I inserted the Service annotation, but I get an error.
Please give me advice.
It is memberDaoMapper code.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.IMemberDAO">
<insert id="insertMember" parameterType="java.util.HashMap">
insert into member values
(
#{id},#{pw},default
)
</insert>
<update id="updateMember" parameterType="java.util.HashMap">
update member set id = #{id}, pw = #{pw}, authority = #{authority}
</update>
<delete id="deleteMember" parameterType="String">
delete from member where id = #{id}
</delete>
<select id="selectOne" parameterType="String" resultType="member">
select * from member where id = #{id}
</select>
<select id="selectAll" parameterType="String" resultType="member">
select * from member
</select>
</mapper>
It is IMemberDao.java code.
package dao;
import java.util.HashMap;
import java.util.List;
import org.mybatis.spring.annotation.MapperScan;
import model.Member;
public interface IMemberDAO
{
public int insertMember(HashMap<String, Object> params);
public int updateMember(HashMap<String, Object> params);
public int deleteMember(String id);
public HashMap<String, Object> selectOne(String id);
public List<HashMap<String, Object>> selectAll();
}
I checked the typo thoroughly, but there was no typo to be found.
What's the problem?
This part of the stacktrace should give you a proper hint of the issue:
org.apache.ibatis.type.TypeException: Could not resolve type alias 'member'
Without the mapper files, I suppose that there is an error in one of them and probably you wrote member in an XML attribute that requires a fully qualified class name.
My suggestion is to search member in those file and you should find it in an incorrect field (mostly like parameterType or resultType)
Looking at the Mapping file that you added, you have resultType="member". As stated above resultType requires a fully qualified class name.
The solutions to your issue are mostly 2:
Modify the resultType to the actual class
<select id="selectOne" parameterType="String" resultType="model.Member">
select * from member where id = #{id}
</select>
<select id="selectAll" parameterType="String" resultType="model.Member">
select * from member
</select>
Add type alias tag for sampleVO class.
<mapper namespace="model.Member">
<typeAlias alias="member" type="model.Member" />
...
</mapper>

rollback the data from first table if exception is thrown

I am using spring mvc and postgres as database
I have requirement to insert diff data into two tables with second table has one columns as foreignkey from first table
I am using jdbc template to connect with database
if some exception happens while inserting into second table i want to rollback the data from first table also
for this do i need use spring transactions concept? please suggest
I tried to implement transactions in this way
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- Define all the service beans that will be created in ePramaan -->
<context:annotation-config />
<tx:annotation-driven/>
<!-- END OF DAO beans Definitions -->
<bean class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="dataSource" />
<!-- Create DataSource Bean -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/ePramaanDB" />
</bean>
<bean id="jdbcSPProfileRepository"
class="in.cdac.epramaan.sp.dao.JdbcSPProfileRepository">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
JdbcSPProfileRepository is a class it contains method to insert data to database
I annotated class with #Transactional
But when i run the server it is throwing exceptions
14:44:01.223 [localhost-startStop-1] ERROR o.s.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jdbcSPProfileRepository': Injection of autowired depende
ncies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: in.cdac.epramaan.common.bd.
MasterConfigBD in.cdac.epramaan.sp.dao.JdbcSPProfileRepository.masterConfigBD; nested exception is org.springframework.beans.factory.NoSuchBeanD
efinitionException: No qualifying bean of type [in.cdac.epramaan.common.bd.MasterConfigBD] found for dependency: expected at least 1 bean which
qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=t
rue)}
#Component
#Transactional
public class JdbcSPProfileRepository implements SPProfileRepository {
private static final Logger logger = LoggerFactory
.getLogger(JdbcSPProfileRepository.class);
#Autowired
private JdbcTemplate jdbcTemplate;
/** The master config bd. */
#Autowired
MasterConfigBD masterConfigBD;
#Autowired
public JdbcSPProfileRepository(DataSource dataSource) {
}
#Override
#Transactional
public SPRegistrationResponse saveSPRegistrationDetails(
final SPRegistration spreg) {
SPRegistrationResponse spRegResponse = new SPRegistrationResponse();
Response response = null;
logger.debug("In saveSPRegistrationDetails : ");
try {/////}catch(){}
}
}
can anybody please suggest the solution
You have several options. One as you suggest is use Spring transactions.
http://simplespringtutorial.com/springDeclarativeTransactions.html
Or you can implemente your own ACID method where sharing the connection between transactions make it atomic. Look this example.
http://www.tutorialspoint.com/jdbc/commit-rollback.htm
The key is only commit on you connection("con") when you want finish your transaction. Then if something goes wrong before finish all your micro transactions, since you did not commit yet nothing will be persisted on your database.

EJB3 interceptor cannot bootstrap context

I'm trying to inject Spring beans into an EJB using
#Interceptors(SpringBeanAutowiringInterceptor.class)
Here's my EJB:
#Stateless
#Interceptors(SpringBeanAutowiringInterceptor.class)
public class processMethodService implements
processMethodService {
#Autowired
private SomeBean bean;
#Schedule(minute = "*/5", hour = "*", persistent = false)
#TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void startProcessing() {
//businesslogic
}
}
And beanRefContext.xml as follows
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean id="ejb-businesslayer.application.context" lazy-init="true"
class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<list>
<value>classpath:/META-INF/spring-config.xml</value>
</list>
</constructor-arg>
</bean> `
beanRefContext.xml,spring-config.xml are under META-INF folder.
when startProcessing is called for every 5 minutes and we are getting the below exception
Exception data: javax.ejb.EJBException: session bean lifecycle interceptor failure;nested exception is:org.springframework.beans.factory.access.BootstrapException: Unable to return specified BeanFactory instance: factory key [null],
from group with resource name [classpath*:beanRefContext.xml];
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [org.springframework.beans.factory.BeanFactory] is defined
Please find the complete exception as below
Exception data: javax.ejb.EJBException: session bean lifecycle interceptor failure;nested exception is: org.springframework.beans.factory.access.BootstrapException: Unable to return specified BeanFactory instance: factory key [null], from group with resource name [classpath*:beanRefContext.xml]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.beans.factory.BeanFactory] is defined`enter code here`
at com.ibm.ejs.container.util.ExceptionUtil.EJBException(ExceptionUtil.java:466)
at com.ibm.ejs.container.SessionBeanO.callLifecycleInterceptors(SessionBeanO.java:288)
at com.ibm.ejs.container.StatelessBeanO.initialize(StatelessBeanO.java:399)
at com.ibm.ejs.container.BeanOFactory.create(BeanOFactory.java:147)
at com.ibm.ejs.container.EJSHome.createBeanO(EJSHome.java:1238)
at com.ibm.ejs.container.EJSHome.createBeanO(EJSHome.java:1356)
at com.ibm.ejs.container.activator.UncachedActivationStrategy.atActivate(UncachedActivationStrategy.java:88)
at com.ibm.ejs.container.activator.Activator.preInvokeActivateBean(Activator.java:615)
at com.ibm.ejs.container.EJSContainer.preInvokeActivate(EJSContainer.java:4205)
at com.ibm.ejs.container.EJSContainer.EjbPreInvoke(EJSContainer.java:3535)
at com.ibm.ejs.container.TimedObjectWrapper.invokeCallback(TimedObjectWrapper.java:110)
at com.ibm.ejs.container.TimerNpListener.doWork(TimerNpListener.java:293)
at com.ibm.ejs.container.TimerNpListener.doWorkWithRetries(TimerNpListener.java:171)
at com.ibm.ejs.container.TimerNpListener.fired(TimerNpListener.java:141)
at com.ibm.ws.asynchbeans.AlarmImpl.callListenerMethod(AlarmImpl.java:427)
at com.ibm.ws.asynchbeans.timer.GenericTimer.run(GenericTimer.java:228)
at com.ibm.ws.asynchbeans.J2EEContext.run(J2EEContext.java:1178)
at com.ibm.ws.asynchbeans.AlarmImpl.runListenerAsCJWork(AlarmImpl.java:249)
at com.ibm.ws.asynchbeans.am._Alarm.fireAlarm(_Alarm.java:333)
at com.ibm.ws.asynchbeans.am._Alarm.run(_Alarm.java:230)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1783)
Caused by: org.springframework.beans.factory.access.BootstrapException: Unable to return specified BeanFactory instance: factory key [null], from group with resource name [classpath*:beanRefContext.xml]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.beans.factory.BeanFactory] is defined
at org.springframework.beans.factory.access.SingletonBeanFactoryLocator.useBeanFactory(SingletonBeanFactoryLocator.java:402)
at org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.getBeanFactoryReference(SpringBeanAutowiringInterceptor.java:160)
at org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.getBeanFactory(SpringBeanAutowiringInterceptor.java:141)
at org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.doAutowireBean(SpringBeanAutowiringInterceptor.java:121)
at org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.autowireBean(SpringBeanAutowiringInterceptor.java:95)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:613)
at com.ibm.ejs.container.interceptors.InterceptorProxy.invokeInterceptor(InterceptorProxy.java:227)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.proceed(InvocationContextImpl.java:548)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.doLifeCycle(InvocationContextImpl.java:273)
at com.ibm.ejs.container.SessionBeanO.callLifecycleInterceptors(SessionBeanO.java:274)
Please guide me on how to resolve this error
The ContextSingletonBeanFactoryLocator is looking for resource classpath*:beanRefContext.xml, so the beanRefContext.xml file has to be in the classpath, ref this link,
Move beanRefContext.xml into a folder that's in the class path and that should solve the problem.
First off, I think removing META-INF should help. Also, I just solved this same issue by moving context in question to /resources directory

Cannot create inner bean 'org.szymon.email.classes.MyMapperClass

I have exception type: org.springframework.beans.factory.BeanCreationException
full stack:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Cannot create inner bean 'org.szymon.email.classes.MyMapperClass#1e222db' of type [org.szymon.email.classes.MyMapperClass] while setting bean property 'defaultViews' with key [1]; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.szymon.email.classes.MyMapperClass] for bean with name 'org.szymon.email.classes.MyMapperClass#1e222db' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.szymon.email.classes.MyMapperClass
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:282)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:121)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1417)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1158)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
my dispatcher-servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:component-scan base-package="org.szymon.email.*" />
<tx:annotation-driven />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="favorPathExtension" value="true"/>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json"/>
<entry key="jsonp" value="application/javascript"/>
</map>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
<bean class="org.szymon.email.classes.MyMapperClass"/>
</list>
</property>
</bean>
</beans>
and my MyMapperClass:
package org.szymon.email.classes;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;
public class MyMapperClass extends MappingJacksonJsonView {
/**
* Default content type. Overridable as bean property.
*/
public static final String DEFAULT_CONTENT_TYPE = "application/javascript";
#Override
public String getContentType() {
return DEFAULT_CONTENT_TYPE;
}
/**
* Prepares the view given the specified model, merging it with static
* attributes and a RequestContext attribute, if necessary.
* Delegates to renderMergedOutputModel for the actual rendering.
* #see #renderMergedOutputModel
*/
#Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
if("GET".equals(request.getMethod().toUpperCase())) {
#SuppressWarnings("unchecked")
Map<String, String[]> params = request.getParameterMap();
if(params.containsKey("callback")) {
response.getOutputStream().write(new String(params.get("callback")[0] + "(").getBytes());
super.render(model, request, response);
response.getOutputStream().write(new String(");").getBytes());
response.setContentType("application/javascript");
}
else {
super.render(model, request, response);
}
}
else {
super.render(model, request, response);
}
}
}
This is continuation of solving problem from question:
Spring RESTful ajax gets error
There is one more interesting thing.
When I put comment on this bean like this:
<!-- <bean class="org.szymon.email.classes.MyMapperClass"/> -->
And create instance of this class in method on my controller and invoke render method of it, then everything is fine... but it is not proper solution.
Please help.
Cheers
The problem seems to be a build - IDE related. I was able to run the project both from IntellIJ IDEA and also by executing then Maven build and placing the produced war in webapps directory of Tomcat.
I suggest you do a Maven clean-compile-package and try again

Spring Rest CXF [bean error] Tomcat

I´m doing a webservice in rest, spring, cxf and tomcat.
Link full project: http://www55.zippyshare.com/v/99585767/file.html
I´ve got this error on bean.
Can´t figure out why is this happening?
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restContainer': Cannot resolve reference to bean 'timeService' while setting bean property 'serviceBeans' with key [0]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'timeService' is defined
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
timeService.java
#Service("timeService")
#Path("/time")
public class TimeService {
#GET
#Produces("text/plain")
public String getDateTime()
{
DateFormatter formatter = new DateFormatter("dd/MM/yyyy hh:mm:ss");
return formatter.print(Calendar.getInstance().getTime(), Locale.getDefault());
}
}
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
<jaxrs:server id="restContainer" address="/">
<jaxrs:serviceBeans>
<ref bean="timeService"/>
</jaxrs:serviceBeans>
</jaxrs:server>
</beans>
These are my files and i can´t find out what is wrong. This is driving me nuts!
The Spring documentation says that you need to add an element to direct the finding of your #Service-annotated beans. For example, if your beans were in the package org.example or one of its sub-packages, you'd use a component scanner configuration in your beans.xml like this:
<context:component-scan base-package="org.example"/>
(As long as it's inside the <beans> element, it's fine whether it goes above or below the <jaxrs:server> element.)

Resources