org.springframework.beans.factory.BeanDefinitionStoreException, How to fix the error? - spring

I am currently studying Spring DI.
But I have not been able to run the project due to some error.
Below is a list of errors.
Exception in thread "main"
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:252)
at org.springframework.context.support.GenericXmlApplicationContext.load(GenericXmlApplicationContext.java:124)
at org.springframework.context.support.GenericXmlApplicationContext.<init>(GenericXmlApplicationContext.java:69)
at Spring_DI.MainClass.main(MainClass.java:15)
Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
The following is the contents of applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="cats" class="Spring_DI.Cats" />
<!-- "Spring_DI.MyCats"클래스를 myCats라는 id를 지정해서 객체(bean)을 생성 -->
<bean id="myCats" class="Spring_DI.MyCats">
<!-- Spring_DI.Cats.MyCats라는 클래스에 있는 필드들의 값을 설정해줌 -->
<property name="cats"><!-- 첫번째 property(필드) -->
<ref bean="cats"/><!-- 이 property는 위에서 생성한 bean(객체)인 cats를 참조한다. -->
</property>
<property name="firstCatName" value="순덕" /><!-- MyCats의 필드의 이름과 값을 설정 -->
<property name="secondCatName" value="나비" />
<property name="firstCatAge" value="1" />
<property name="secondCatAhttps://stackoverflow.com/jobs?med=site-ui&ref=jobs-tabge" value="2" />
</bean>
</beans>
Here is the contents of the java file.
package Spring_DI;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
//bean을 설정한 xml파일이 있는 위치 지정
String configLocation = "classpath:applicationContext.xml";
//지정한 위치를 참고하여 설정파일을 얻어옴
AbstractApplicationContext ctx =
new GenericXmlApplicationContext(configLocation);
//설정파일에서 bean을 가져옴
//getBean()를 이용해서 MyCats타입에서 myCats를 얻어와서 객체를 생성
// = 방법1 예제처럼 직접 생성이 아닌 외부에서 얻어옴(주입을 시켜줌)
MyCats myCat = ctx.getBean("myCats",MyCats.class);
//호출
myCat.catsNameInfo();
myCat.catsAgeInfo();
}
}
The following is the project structure.
enter image description here
How can I handle the above error?
And why does the above error occur?
Please let me know how to fix the problem.

As per the screenshot, your project is maven project. So the resources(any other files than source files) should be placed in src/main/resources.When Maven build your project, it expects to find only Java source files under src/main/java, and ignores all the other files.

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>

spring integration-mqtt type converter issue

Trying to run the sample spring-integration mqtt project from web.
I have imported the mqtt-context in root context. After the war is deployed I am running the RunMqtt.java file. But getting the following issue. If running in standalone mode , the same file does not give any issue.
Stack Trace
Creating instance of bean 'startCaseAdapter'
16:50:54.147 DEBUG [main][org.springframework.beans.BeanUtils] No property editor [org.springframework.integration.mqtt.core.MqttPahoClientFactoryEditor] found for type org.springframework.integration.mqtt.core.MqttPahoClientFactory according to 'Editor' suffix convention
16:50:54.148 TRACE [main][org.springframework.beans.TypeConverterDelegate] Field [topic] isn't an enum value
java.lang.NoSuchFieldException: topic
at java.lang.Class.getField(Class.java:1579)
at org.springframework.beans.TypeConverterDelegate.attemptToConvertStringToEnum(TypeConverterDelegate.java:336)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:257)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:107)
at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:64)
at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:47)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:706)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1133)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1036)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:505)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:725)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.iux.ieg.test.mqtt.RunMqtt.test(RunMqtt.java:24)
at com.iux.ieg.test.mqtt.RunMqtt.main(RunMqtt.java:46)
16:50:54.150 TRACE [main][org.springframework.beans.factory.support.DefaultListableBeanFactory] Ignoring constructor [public org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter(java.lang.String,java.lang.String,org.springframework.integration.mqtt.core.MqttPahoClientFactory,java.lang.String[])] of bean 'startCaseAdapter': org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'startCaseAdapter': Unsatisfied dependency expressed through constructor argument with index 2 of type [org.springframework.integration.mqtt.core.MqttPahoClientFactory]: Could not convert constructor argument value of type [java.lang.String] to required type [org.springframework.integration.mqtt.core.MqttPahoClientFactory]: Failed to convert value of type 'java.lang.String' to required type 'org.springframework.integration.mqtt.core.MqttPahoClientFactory'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.springframework.integration.mqtt.core.MqttPahoClientFactory]: no matching editors or conversion strategy found
16:50:54.150 TRACE [main][org.springframework.beans.TypeConverterDelegate] Converting String to [class [Ljava.lang.String;] using property editor [org.springframework.beans.propertyeditors.StringArrayPropertyEditor#821075]
16:50:54.150 TRACE [main][org.springframework.beans.TypeConverterDelegate] Field [clientId] isn't an enum value
java.lang.NoSuchFieldException: clientId
at java.lang.Class.getField(Class.java:1579)
at org.springframework.beans.TypeConverterDelegate.attemptToConvertStringToEnum(TypeConverterDelegate.java:336)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:257)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:107)
at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:64)
at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:47)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:706)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1133)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1036)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:505)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:725)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.iux.ieg.test.mqtt.RunMqtt.test(RunMqtt.java:24)
at com.iux.ieg.test.mqtt.RunMqtt.main(RunMqtt.java:46)
Configuration
Web-application-config.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
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.xsd">
<!-- This file will be the root context file for web app. All other context
will be imported here -->
<!-- Security context . Now the spring security with basic authentication
implemented. OAuth2 will be implemented -->
<import resource="security-config.xml" />
<!-- rest service call context -->
<import
resource="classpath:META-INF/spring/integration/rest/applicationContext-http-int.xml" />
<!-- Sftp context -->
<import
resource="classpath:META-INF/spring/integration/sftp/SftpInboundReceive-context.xml" />
<import
resource="classpath:META-INF/spring/integration/sftp/SftpOutboundTransfer-poll.xml" />
<!-- mqtt context -->
<import resource="classpath:META-INF/spring/integration/mqtt/mqtt-context.xml" />
<!-- Mail Context -->
<import
resource="classpath:META-INF/spring/integration/mail/mail-imap-idle-config.xml" />
<import
resource="classpath:META-INF/spring/integration/mail/mail-pop3-config.xml" />
<!--Component scan base package -->
<context:component-scan base-package="com.iux.ieg" />
<!-- All the property configuration moved to parent context file to solve
the propert not found exception -->
<!-- <context:property-placeholder order="1" location="classpath:/sftpuser.properties,
classpath:/sftpfile.properties,classpath:/resthttp.properties" ignore-unresolvable="true"/> -->
<context:property-placeholder order="0"
location="classpath:/sftpfile.properties" ignore-unresolvable="true" />
<context:property-placeholder order="1"
location="classpath:/sftpuser.properties" ignore-unresolvable="true" />
<context:property-placeholder order="2"
location="classpath:/resthttp.properties" ignore-unresolvable="true" />
<context:property-placeholder order="3"
location="classpath:/mqtt.properties" ignore-unresolvable="true" />
<context:property-placeholder order="4"
location="classpath:/mail.properties" />
</beans>
mqtt-context.xml
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/integration/mqtt http://www.springframework.org/schema/integration/mqtt/spring-integration-mqtt-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:property-placeholder
location="classpath:/mqtt.properties" ignore-unresolvable="true" />
<!-- intercept and log every message -->
<int:logging-channel-adapter id="logger"
level="ERROR" />
<int:wire-tap channel="logger" />
<!-- Mark the auto-startup="true" for starting MqttPahoMessageDrivenChannelAdapter from configuration -->
<int-mqtt:message-driven-channel-adapter
id="startCaseAdapter" client-id="clientId" url="${mqtt.brokerurl}"
topics="topic" channel="startCase" auto-startup="true" />
<int:channel id="startCase" />
<int:service-activator id="startCaseService"
input-channel="startCase" ref="mqttCaseService" method="startCase" />
<bean id="mqttCaseService" class="com.iux.ieg.mqtt.MqttCaseService" />
MqttCaseService.java
import org.apache.log4j.Logger;
public class MqttCaseService {
private static Logger logger = Logger.getLogger(MqttCaseService.class);
public void startCase(String message){
logger.debug(message);
}
}
RunMqtt.java
public class RunMqtt {
private static Logger logger = Logger.getLogger(RunMqtt.class);
//#Test
public void test() throws MqttException{
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext("/META-INF/spring/integration/mqtt/mqtt-context.xml");
logger.debug(context);
//MqttPahoMessageDrivenChannelAdapter startCaseAdapter = (MqttPahoMessageDrivenChannelAdapter)context.getBean("startCaseAdapter");
//Uncomment to stop the adapter manually from program
//startCaseAdapter.start();
//DefaultMqttPahoClientFactory mqttClient = (DefaultMqttPahoClientFactory)ac.getBean("clientFactory");
DefaultMqttPahoClientFactory mqttClient = new DefaultMqttPahoClientFactory();
MqttClient mclient = mqttClient.getClientInstance("tcp://*messagebrokerurl*:1883", "JavaSample");
String data = "This is what I am sending in 2nd attempt";
MqttMessage mm = new MqttMessage(data.getBytes());
mm.setQos(1);
mclient.connect();
mclient.publish("topic",mm);
mclient.disconnect();
//Uncomment to stop the adapter manually from program
//startCaseAdapter.stop();
}
public static void main(String[] args) {
try {
new RunMqtt().test();
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
the sample spring-integration mqtt project
Which sample?
Please show your configuration.
EDIT:
It looks like Spring is having trouble determining which constructor to use.
Try adding
<bean id="clientFactory" class="org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory" />
and add client-factory="clientFactory" to the message-driven adapter.

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

applicationContext could path could not be resolved

i am getting this error, when i define the the applicationContext inside my spring simple database connection code.
but when i place the applicationContext where the java (DatabaseTestConnection.java) resides, it connects without any issues.
Exception in thread "main"
org.springframework.beans.factory.BeanDefinitionStoreException:
IOException parsing XML document from class path resource
[applicationContext.xml]; nested exception is
java.io.FileNotFoundException: class path resource
[applicationContext.xml] cannot be opened because it does not exist
Source
applicationContext.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!--bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" /-->
<bean id="databaseTestConnection" class="DatabaseTestConnection">
<property name="dataSource" ref="externalDataSource"/>
</bean>
<bean id="externalDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" scope="singleton" destroy-method="close">
<property name="driverClassName" value="sun.jdbc.odbc.JdbcOdbcDriver"/>
<property name="url" value="jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb, *.accdb);DBQ=C://Users//gopc//Documents//odbc_sql.accdb"/>
<property name="username" value=""/>
<property name="password" value=""/>
</bean>
<!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
</beans>
DatabaseTestConnection.java
import java.util.*;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class DatabaseTestConnection {
private JdbcTemplate jt;
public void setDataSource(DataSource dataSource) {
this.jt = new JdbcTemplate(dataSource);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
DatabaseTestConnection bn = (DatabaseTestConnection) bf.getBean("databaseTestConnection");
int count = bn.jt.queryForInt("select count(*) from log_entry");
System.out.println("cgk count:" + count);
List <Map <String,Object> > ob = bn.jt.queryForList("select * from log_entry", args);
System.out.println("cgk size:" + ob.size());
for (Map<String,Object> entry: ob )
{
System.out.println("ID:" + entry.get("ID"));
System.out.println("DateCol:" + entry.get("DateCol"));
System.out.println("Completed:" + entry.get("Completed"));
}
}
}
Anyway you are just testing in local so,you can do this to load from context path
ApplicationContext ctx = new FileSystemXmlApplicationContext("C:\\workspace\\src\\main\\webapp\\WEB-INF\\applicationContext.xml"); // in your case path to your applicationContext.xml file in your local.
The applicationContext.xml file should be located inside the WEB-INF/classes folder.
Your configuration says the applicationContext.xml file is in the classpath. The classpath references to WEB-INF/classes directory in an servlet application.

Unable to Import persistence.xml within applicationContext.xml file

I'm using eclipse juno IDE
I have Java application which have src folder. within the folder I have:
1) applicationContext.xml
2) persistence.xml
I also have DBInterface and i implemented it with JPA.
Now in the applicationContext.xml file I have a bean for the JPA implemention.
When I tried to inject the bean i got an excpetion that said something like "No Persistence Provider was found".
So I tried to import the persistence file within the applicationContext file but i'm getting another exception.
applicationContext.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:aop="http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
xmlns:context="http://www.springframework.org/schema/context/spring-context-2.5.xsd"
xmlns:flow="http://www.springframework.org/schema/webflow-config/spring-webflow-config-1.0.xsd"
xmlns:jms="http://www.springframework.org/schema/jms/spring-jms-2.5.xsd"
xmlns:jee="http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"
xmlns:lang="http://www.springframework.org/schema/lang/spring-lang-2.5.xsd"
xmlns:osgi="http://www.springframework.org/schema/osgi/spring-osgi.xsd"
xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
xmlns:util="http://www.springframework.org/schema/util/spring-util-2.5.xsd"
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
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/aop/spring-aop-2.5.xsd/spring-spring-aop-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/context/spring-context-2.5.xsd/spring-spring-context-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/webflow-config/spring-webflow-config-1.0.xsd http://www.springframework.org/schema/webflow-config/spring-webflow-config-1.0.xsd/spring-spring-webflow-config-1.0.xsd-2.5.xsd
http://www.springframework.org/schema/jms/spring-jms-2.5.xsd http://www.springframework.org/schema/jms/spring-jms-2.5.xsd/spring-spring-jms-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/jee/spring-jee-2.5.xsd/spring-spring-jee-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd http://www.springframework.org/schema/lang/spring-lang-2.5.xsd/spring-spring-lang-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/osgi/spring-osgi.xsd http://www.springframework.org/schema/osgi/spring-osgi.xsd/spring-spring-osgi.xsd-2.5.xsd
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/tx/spring-tx-2.5.xsd/spring-spring-tx-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/util/spring-util-2.5.xsd http://www.springframework.org/schema/util/spring-util-2.5.xsd/spring-spring-util-2.5.xsd-2.5.xsd">
<bean id="JPA" class="pack.jpa.JPAQueries"/>
<import resource="persistence.xml"/>
</beans>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit transaction-type="RESOURCE_LOCAL" name="MyJPA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>pack.bl.Travels</class>
<class>pack.bl.Example</class>
<properties> <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/taxis"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
</properties>
</persistence-unit>
mainClass
public class Program {
/**
* #param args
*/
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
DBInterface dao = (DBInterface)context.getBean("JPA",JPAQueries.class);
dao.retrieveRecords();
}
Exception
Exception in thread "main"
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration
problem: Failed to import bean definitions from relative location [persistence.xml]
Offending resource: class path resource [applicationContext.xml]; nested exception is
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration
problem: Unable to locate Spring NamespaceHandler for XML schema namespace
[http://java.sun.com/xml/ns/persistence]
Offending resource: class path resource [persistence.xml]
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:76)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:271)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:196)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:181)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:140)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:111)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:243)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:131)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:527)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:441)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at pack.program.Program.main(Program.java:16)
Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://java.sun.com/xml/ns/persistence]
Offending resource: class path resource [persistence.xml]
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:317)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1428)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1421)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:190)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:140)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:111)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:255)
... 20 more
Your attempt to use persistence.xml as a Spring config makes absolutely no sense, because persistence.xml is not a Spring config.
If you want to use JPA with Spring, you need to put persistence.xml into META-INF folder inside your source folder, and declare LocalContainerEntityManagerFactory in applicationContext.xml:
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name = "persistenceUnitName" value = "MyJPA" />
</bean>
Then you can inject EntityManager into your Spring bean using #PersistenceContext:
#PersistenceContext
private EntityManager em;
See also:
13.5 JPA
It should be imported as follows:
<import resource="classpath:META-INF/persistence.xml"/>
assuming the persistence.xml is present in META-INF directory which is a top-level directory in one of your jars on the classpath.
Ok, I Solved this..
What i did is to put the persistence.xml file within the META-INF folder
as vikdor and axtavt suggested. but in the application context i didn't import any file..
just wrote this
<bean id="JPA" class="pack.jpa.JPAQueries"/>
and its work!

Resources