I would like to get advice on Spring BeanCreationException Error - spring

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>

Related

Spring NotWritablePropertyException and Invalid property 'lazyInit' of bean JndiObjectFactoryBean

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"/>

Failure to find Class - Spring 3, Hibernate 3, JPA

It appears that my class is not found by the JPA infrstructure. Im guessing Spring just cant find it? I have tried package scanning and adding the class to persistence.xml. Anyone out there have any thoughts on what else I can try to allow my select to find that class (and the underlying table)?
thanks!
Here is the code.
persistence.xml
<persistence-unit name="myApp" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:joss/datasources/myDB</jta-data-source>
<!-- get a special error with this in - see below -->
<!-- <class>com.src.dao.User</class> -->
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.archive.autodetection" value="class,hbm" />
UserDAO Code that causes error:
final String queryString="select model from " +User.class.getSimpleName() + " model where model."propertyName+"=:propertyValue";
return getJpaTemplate().executeFind(new JpaCallback() {
#Override
public Object doInJpa(EntityManager em) throws PersistenceException {
//this line causes the error below
Query query = em.createQuery(queryString);
Error Thrown:
201-06-10 18:59:32,736 ERROR [UserDAO] find by property name failed
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [select model from User model where model.value= :propertyValue]; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException:User is not mapped [select model from User model where model.value= :propertyValue]
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:286)
applicationcontext.xml
<context:annotation-config />
<context:component-scan base-package="com.src.dao" />
also tried it within a bean
<beans:bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" packagesToScan="com.src.dao">
<beans:property name="persistenceUnitName" value="myApp" />
<beans:property name="packagesToScan" value="com.src.dao" />
</beans:bean>
User Class:
package com.src.dao
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
* User Entity
*
* #author MyEclipse Persistence Tools
*/
#Entity
#Table (name="USERS", schema="myDb")
public class User extends AbstractUser implements java.io.Serializable, Comparable<User> {
Adding class to persistence.xml:
When I add in <class> to my persistence.xml I get the following on app deploy. The war never deploys:
Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/configs/spring/stu-hibernate.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: myApp] Unable to build EntityManagerFactory
at org.springframework.beans.factory.annotation.AutoWiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
Finally figured it out. It appears that based on my Spring version (3.0.5) I really needed to add the class in persistence.xml. However, my above error would not allow that. Turns out... I needed to add ALL the classes in that package to persistence.xml (minus the DAO's). Once I did that the app started up and worked!
Not sure why all of them were needed.

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

error working with spring restful service

i am new to spring restful service and i want to get the result in differnt format when i type the below url-----
localhost:7001/SpringRestService/restful/methodName/ALL/ALL/ALL/ALL.xml
localhost:7001/SpringRestService/restful/methodName/ALL/ALL/ALL/ALL.json
localhost:7001/SpringRestService/restful/methodName/ALL/ALL/ALL/ALL.pdf
but i am getting the below error when i start my server----
<Servlet: "SpringRest" failed to preload on startup in Web application: "SpringRestService".
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0' defined in ServletContext resource [/WEB-INF/SpringRest-servlet.xml]: Cannot create inner bean 'org.springframework.web.servlet.view.UrlBasedViewResolver#20e0f98' of type [org.springframework.web.servlet.view.UrlBasedViewResolver] while setting bean property 'viewResolvers' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.view.UrlBasedViewResolver#20e0f98' defined in ServletContext resource [/WEB-INF/SpringRest-servlet.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: Property 'viewClass' is required
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:1391)
Truncated. see log file for complete stacktrace
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.view.UrlBasedViewResolver#20e0f98' defined in ServletContext resource [/WEB-INF/SpringRest-servlet.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: Property 'viewClass' is required
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:532)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:271)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:121)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
Truncated. see log file for complete stacktrace
java.lang.IllegalArgumentException: Property 'viewClass' is required
-----------------------springRest-servlet.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Specify a view resolver for JSP files-->
<bean id="viewResolvers" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/view/" p:suffix=".jsp" />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="xml" value="application/xml"/>
<entry key="html" value="text/html"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver"/>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</list>
</property>
</bean>
</beans>
-----------------------------my controller class------------------------------
below is my controller class
package org.nea.rest.unsr;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nea.ia.services.util.uniserv.UniServGrantInfo;
import org.nea.spring.services.interfaces.uniservs.UniservSearchInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class HelloWorldController1 {
#Autowired
UniservSearchInterface uniservService;
public UniservSearchInterface getUniservService() {
return uniservService;
}
public void setUniservService(UniservSearchInterface uniservService) {
this.uniservService = uniservService;
}
protected final Log logger = LogFactory.getLog(getClass());
/* commented
#RequestMapping(value = "/showAllGrants/{userName}/{year}/{status}/{stateId}", method = RequestMethod.GET)
public #ResponseBody
List<UniServGrantInfo> getTextFromURL(#PathVariable("userName") String userName, #PathVariable("year") String year,
#PathVariable("status") String status, #PathVariable("stateId") String stateId) {
List<UniServGrantInfo> grantInfoList = new ArrayList<UniServGrantInfo>();
grantInfoList = uniservService.showAllgrants(userName, year, status, stateId);
return grantInfoList;
}
*/
#RequestMapping(value = "/showAllGrants/{userName}/{year}/{status}/{stateId}", method = RequestMethod.GET)
public ModelAndView getTextFromURL(#PathVariable("userName") String userName, #PathVariable("year") String year,
#PathVariable("status") String status, #PathVariable("stateId") String stateId) {
List<UniServGrantInfo> grantInfoList = new ArrayList<UniServGrantInfo>();
grantInfoList = uniservService.showAllgrants(userName, year, status, stateId);
ModelAndView model = new ModelAndView("index");
//ModelAndView mav = new ModelAndView();
// mav.setViewName("index");
// mav.addObject("sampleContentList", grantInfoList);
return model;
}
}
can anybody help me telling where i am doing wrong or if i am missing any required jar file.
Your configuration for the UrlBasedViewResolver is incomplete. The exception states that the property ‘viewClass‘ is missing. For example a complete configuration:
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"/>
</bean>

Autowired Fails with Spring Junit Test

Writing Junit Tests for my spring application. Because I am new at this I tried starting off by writing a Unit Test for a DAO class that I know works (ran it in JBoss). However, I cannot get it to work as a Unit Test in Eclipse. I keep getting an "Error creating bean... Could not autowire field: NoSuchBeanDefinition".
I saw errors similar to this on StackOverflow and other sites and it always ended up being a syntax error or attempting to autowire the Implementation of the interface as opposed to the Interface, etc. I don't see any of those errors with my code.
I did download Spring-test.jar separately from the Spring configuration that came with the project. Both are from Spring 2.5 however, so I don't think that should be an issue :/
Eclipse comes bundled with JUnit 4.8 and Spring Unit Test doesn't work with that so I downgraded my JUnit to use 4.4
One thing to consider... if you look at the code for my Unit Test you will notice that I autowire two fields: a SimpleJdbcTemplate at the Query Service I want to test. Well if I remove the DrugDao and all references to it, then the SimpleJdbcQuery auto-wires just fine.
Here is the stacktrace for your review:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tst.hcps.glucosemanagement.dataaccess.DrugDaoTest': Autowiring of fields failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.hcps.glucosemanagement.repository.meds.DrugDao tst.hcps.glucosemanagement.dataaccess.DrugDaoTest.dQuery; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.hcps.glucosemanagement.repository.meds.DrugDao] is defined: Unsatisfied dependency of type [interface com.hcps.glucosemanagement.repository.meds.DrugDao]: expected at least 1 matching bean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:243)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:959)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:329)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:127)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:85)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:95)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:139)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.hcps.glucosemanagement.repository.meds.DrugDao tst.hcps.glucosemanagement.dataaccess.DrugDaoTest.dQuery; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.hcps.glucosemanagement.repository.meds.DrugDao] is defined: Unsatisfied dependency of type [interface com.hcps.glucosemanagement.repository.meds.DrugDao]: expected at least 1 matching bean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:435)
at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(InjectionMetadata.java:105)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:240)
... 18 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.hcps.glucosemanagement.repository.meds.DrugDao] is defined: Unsatisfied dependency of type [interface com.hcps.glucosemanagement.repository.meds.DrugDao]: expected at least 1 matching bean
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:613)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:412)
... 20 more
Here is the Interface and Implementation:
DrugDao.java
package com.hcps.glucosemanagement.repository.meds;
import java.util.List;
import com.hcps.glucosemanagement.domain.meds.Drug;
public interface DrugDao {
public List<Drug> searchDrugsByPrimaryName(String facilityId, String name);
public List<Drug> searchDrugs(String facilityId, String primaryName, String secondaryName);
}
SpringJdbcDrugQuery.java
package com.hcps.glucosemanagement.repository.meds;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.stereotype.Service;
import com.hcps.glucosemanagement.domain.meds.Drug;
import com.hcps.glucosemanagement.repository.DaoOperations;
#Service
public class SpringJdbcDrugQuery extends DaoOperations implements DrugDao {
private static final Logger logger = Logger.getLogger(SpringJdbcDrugQuery.class);
public List<Drug> searchDrugsByPrimaryName(String facilityId, String name)
{
return searchDrugs(facilityId, name, null);
}
public List<Drug> searchDrugs(String facilityId, String primaryName, String secondaryName)
{
List<Drug> results = null;
StringBuffer sql = new StringBuffer();
HashMap<String, Object> namedParameters = new HashMap<String, Object>();
if(primaryName==null) return null;
sql = new StringBuffer();
sql.append("SELECT");
...
results = simpleJdbcTemplate.query(sql.toString(), new DrugMapper(),
return results;
}
private static final class DrugMapper implements ParameterizedRowMapper<Drug>
{
public Drug mapRow(ResultSet rs, int rowNum) throws SQLException {
Drug drug = new Drug();
drug.setFacilityId(rs.getString("FACILITY_ID"));
drug.setPrimaryName(rs.getString("PRIMARY_NAME"));
drug.setSecondaryName(rs.getString("SEC_NAME"));
return drug;
}
}
}
DrugDaoTest2.java (located in a separate source folder at first, then tried it in the same folder)
package com.hcps.glucosemanagement.repository.meds;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.hcps.glucosemanagement.domain.meds.Drug;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={
"classpath:common-test.xml"
})
public class DrugDaoTest2 {
#Autowired
DrugDao dQuery;
#Autowired
SimpleJdbcTemplate queryTemplate;
#Test public void glucoseFetch() {
List<Drug> rslts = dQuery.searchDrugsByPrimaryName(null, "INSU*");
assertTrue(rslts.size()>0);
int i=0;
System.out.println(i);
}
public void setDrugDao(DrugDao drugDao) {
this.dQuery = drugDao;
}
}
common-test.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
>
<!--
Test configuration for Spring/JUnit Testing
-->
<bean id="contextApplicationContextProvider" class="com.hcps.glucosemanagement.spring.ApplicationContextProvider" />
<bean id="jmxExporter" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false">
<property name="beans">
<map>
<entry key="bean:name=Log4jJmxServiceMBean" value-ref="glucosemanagement.Log4jJmxService" />
</map>
</property>
</bean>
<bean id="glucosemanagement.Log4jJmxService" class="com.hcps.glucosemanagement.logging.Log4jJmxService" />
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
<bean id="parameterMappingInterceptor" class="org.springframework.web.portlet.handler.ParameterMappingInterceptor" />
<bean id="viewResolverCommon" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:order="2"
p:cache="false"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp"
/>
<bean id="defaultExceptionHandler" class="org.springframework.web.portlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="../error"/>
<property name="exceptionMappings">
<props>
<prop key="javax.portlet.PortletSecurityException">notAuthorized</prop>
<prop key="javax.portlet.UnavailableException">notAvailable</prop>
</props>
</property>
</bean>
<bean id="simpleParameterJdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="hciDataSource" />
</bean>
<bean id="hciDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#//vir-tst.com:1521/qar01.world" />
<property name="username" value="ccuser" />
<property name="password" value="bueno" />
<property name="maxActive" value="30" />
<property name="maxWait" value="30" />
<property name="maxIdle" value="30" />
</bean>
</beans>
My mistake: there was another Spring Configuration file referenced elsewhere that I missed. Adding this field and defining setters in my Unit Test for any autowired fields solved the problem.
I am using this checklist now when these types of errors occur:
Make sure that implementing class of Interface type uses “#Service”
annotation
Make sure beans are configured properly in the XML:
Simplest way is to use:
<context:component-scan base-package="com.customization.packagename" />
This adds all classes under the package name
Or create XML Bean Definitions
I had the similar issue and found that while I could AutoWire classes successfully in Eclipse, surefire required only interfaces to be AutoWired. Especially this occurs only when using Cobertura for instrumenting, so pretty sure there is something wrong with the proxy generation. For now, I have just introduced a new interface as it was appropriate for my use-case but there should definitely be another appropriate solution.
Add a bean definition of type SpringJdbcDrugQuery to common-test.xml
I encounter this problem too, and I just add setter, then it works well.

Resources