Unable to create mongotemplate in spring - spring

Error:
19-Feb-2016 00:00:16.731 SEVERE [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.data.mongodb.core.MongoTemplate com.test.app.service.PersonService.mongoTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.data.mongodb.core.MongoTemplate]: Constructor threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.core.convert.support.ConversionServiceFactory.createDefaultConversionService()Lorg/springframework/core/convert/support/GenericConversionService;
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.2.xsd">
<context:component-scan base-package="com.test.app" />
<mvc:annotation-driven/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- Factory bean that creates the Mongo instance -->
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<property name="host" value="localhost" />
</bean>
<!-- MongoTemplate for connecting and querying the documents in the database -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongo" ref="mongo" />
<constructor-arg name="databaseName" value="test" />
</bean>
<!-- Use this post processor to translate any MongoExceptions thrown in #Repository annotated classes -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="personController" class="com.test.app.controller.PersonController" />
<bean id="personService" class="com.test.app.service.PersonService" />
<bean id="person" class="com.test.app.model.Person" />
</beans>
I am seeing many posts regarding this error , but no answers to fix this.

The version of spring-core need match the version of spring-data.
Below is my part pom.xml:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<!-- Spring data mongodb -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.8.2.RELEASE</version>
</dependency>
It's fixed.

It's almost the same thing only annotation driven. In the Supplier I'm just casting mongoTemplate (You may not want that). So If you use the spring config everything should work fine.
Regarding your version in XML try creating the mongo factory from SimpleMongoDbFactory with a MongoClient and the database name, Then just give your MongoTemplate bean your factory, and that's it.
Spring Config:
#Configuration
public class SpringConfig {
#Bean
public MongoDbFactory mongoDbFactory() throws UnknownHostException{
return new SimpleMongoDbFactory(new MongoClient(),"games");
}
#Bean
public MongoTemplate mongoTemplate() throws UnknownHostException{
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
return mongoTemplate;
}
}
After that I created a supplier (Google Guava in this case) which may not be needed in your case
public class MongoOperationSupplier implements Supplier<MongoOperations>{
#Override
public MongoOperations get() {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
return mongoOperation;
}
}
An annotated class:
#Document(collection="game_suspicious_event")
public class SuspiciousEvent {
#Id
private String id;
private String apiKey;
private String userUniqueId;
private Date date;
private String ip;
private String additionalInformation;
public SuspiciousEvent(){}
public SuspiciousEvent(String apiKey,String userUniqueId,Date date, String ip, String additionalInformation){
this.apiKey=apiKey;
this.userUniqueId=userUniqueId;
this.date=date;
this.ip=ip;
this.additionalInformation=additionalInformation;
}
public String getApiKey() {
return apiKey;
}
}
Then to use:
final MongoOperations mo = new MongoOperationSupplier().get();
mo.save(new SuspiciousEvent(......));
Hope it helps.

Related

No qualifying bean of type is defined [duplicated]

Currently I experiencing the BeanNameAware interface are not working if AOP is implementing in my Knight Bean.
Why is this happening? because of CGLib conflict? For reference I am using spring framework 3
here is my bean code
public class BraveKnight implements BeanNameAware{
private Quest quest;
public void setQuest(Quest mockQuest){
this.quest = mockQuest;
}
public void embarkOnQuest(){
quest.embark();
}
#Override
public void setBeanName(String beanName) {
System.out.println(beanName +" bean has been initialized..." );
}
}
Application context
<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"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="knight" class="com.springinaction.knights.BraveKnight">
<property name="quest" > <ref bean="quest"/> </property>
</bean>
<bean id="quest" class="com.springinaction.knights.Quest">
<constructor-arg value="#{T(System).out}" />
</bean>
<bean id="minstrel" class="com.springinaction.knights.Minstrel">
<constructor-arg value="#{T(System).out}" />
</bean>
<aop:config>
<aop:aspect ref="minstrel">
<aop:pointcut id="embark" expression="execution(* *.embarkOnQuest(..))" />
<aop:before pointcut-ref="embark" method="singBeforeQuest" />
<aop:after pointcut-ref="embark" method="singAfterQuest" />
</aop:aspect>
</aop:config>
</beans>
[Edit 1]: and here is my main class, I tried getBean with string and class but seems no big differences
public static void main(String[] args) throws Exception{
AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring/web/*.xml");
BraveKnight knight = context.getBean(BraveKnight.class);
knight.embarkOnQuest();
context.close();
}
and my result is getting these errors so I am suspecting CGLib conflict with Spring AOP?
quest bean has been initialized...
knight bean has been initialized...
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.springinaction.knights.BraveKnight] is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:295)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1125)
at com.springinaction.knights.KnightMain.main(KnightMain.java:10)

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.

Spring Data JPA. Repositories Inheritance, throws BeanCreationException, NullPointerException

So I started using Spring Data JPA, I find it very easy to use at first especially with simple POJO entities, I managed to perform simple CRUD operations with a single entity (Person), but as I dig deeper with my design(inheritance), I'm starting to have a hard time dealing with Spring JPA repositories when it comes to inheritance design.
Legend :
POJOs
Repositories
Sample class that uses those two above
Exceptions thrown
xml configuration
Person class (base, abstract class)
#MappedSuperclass
public abstract class Person {
..properties, getters and setters with hibernate annotations
}
Student class (child, extends Person)
#Entity
#Table(name = "STUDENT")
public class Student extends Person {
.. properties, getters and setters SPECIFIC for a student
}
REPOSITORIES
PersonRepository (base, parent repository)
public interface PersonRepository<T extends Person, ID extends Serializable> extends JpaRepository<T, ID> {
}
StudentRepository (child, extends PersonRepository)
public interface StudentRepository extends PersonRepository<Student, Integer>{
}
Sample class
#Service ("manager")
public class Manager {
#SuppressWarnings("rawtypes")
#Resource (name = "personRepository")
private PersonRepository personRepository;
#SuppressWarnings("unchecked")
public void savePerson(Person p) {
personRepository.save(p);
}
}
Exceptions thrown
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'manager': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personRepository': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:308)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
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:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at edu.main.Main.main(Main.java:12)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personRepository': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:175)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:103)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1512)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:313)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:446)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:420)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:545)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:155)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:305)
... 13 more
Caused by: java.lang.NullPointerException
at java.lang.Class.isAssignableFrom(Native Method)
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:58)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:145)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:83)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:66)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:146)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:120)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:39)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:168)
xml Configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:repository="http://www.springframework.org/schema/data/repository"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.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-4.0.xsd
http://www.springframework.org/schema/data/repository
http://www.springframework.org/schema/data/repository/spring-repository.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<context:annotation-config />
<context:component-scan base-package="edu.service" />
<jpa:repositories base-package="edu.repository" />
<tx:annotation-driven />
<context:property-placeholder
location="classpath:properties/database.properties"
ignore-unresolvable="false" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>edu.domain</value>
</list>
</property>
<property name="persistenceUnitName" value="personPU"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
I'm trying to to find a specific words to search for a similar problem, but no luck, what could be the problem that causes my repository to not have a repository bean(a NullPointerException/BeanCreationException)?. And another thing I want to add, and am I doing something wrong with my design pattern? should I reflect my POJOs inheritance pattern to my Repositories? I'm trying to make my PersonRepository perform operations on my POJO/Entites that are children of the Person class(abstract parent), thats why I came up with the idea of repository inheritance. My specific goal is, Persist/Perform CRUD on any objects that extends the Person using PersonRepository. Any help/suggestion/comments is greatly appreciated. Please. Thank you so much
I believe the PersonRepository should be annotated with #NoRepositoryBean.
In my application I've done it this way:
Parent:
#NoRepositoryBean
public interface UserRepository<T> extends JpaRepository<T, Long> {
}
Child:
#Repository
public interface EmployeeRepository extends UserRepository<Employee> {
}
Hope it helps.

Spring Autowiring not working - BeanCreationException

I want to integrate Spring with Hibernate. I am new to both technologies. At the moment I get an error like this:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public service.UserService controller.HomeController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [service.UserService] 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)}
Can anybody help me, please?
package controller;
#Controller
public class HomeController {
#Autowired
private UserService userService;
#RequestMapping("/register")
public ModelAndView getRegisterForm(#ModelAttribute("user") User user,
BindingResult result) {
ArrayList<String> gender = new ArrayList<String>();
gender.add("Male");
gender.add("Female");
ArrayList<String> city = new ArrayList<String>();
city.add("Delhi");
city.add("Kolkata");
city.add("Chennai");
city.add("Bangalore");
Map<String, Object> model = new HashMap<String, Object>();
model.put("gender", gender);
model.put("city", city);
System.out.println("Register Form");
return new ModelAndView("Register", "model", model);
}
#RequestMapping("/saveUser")
public ModelAndView saveUserData(#ModelAttribute("user") User user,
BindingResult result) {
userService.addUser(user);
System.out.println("Save User Data");
return new ModelAndView("redirect:/userList.html");
}
#RequestMapping("/userList")
public ModelAndView getUserList() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", userService.getUser());
return new ModelAndView("UserDetails", model);
}
}
package service;
#Service
public class UserServiceImpl implements UserService {
#Autowired
UserDao userDao;
#Override
public void addUser(User user) {
userDao.saveUser(user);
}
#Override
public List<User> getUser() {
return userDao.getUser();
}
}
spring-servlet Code:
Hi need a Spring ,Hibernate integration example for my new project.so i have copied this from a website.and i did some modifications in that ..It's not working please help me
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="controller" />
<tx:annotation-driven/>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="myydao" class="dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean name="/user/*.htm" class="controller.HomeController" >
<property name="UserDao" ref="mydao" />
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
I assume that you haven't added the bean to your Spring Application Context
If you are using xml, you need to do this by adding something like the following to the xml file:
<bean class="service.UserServiceImpl" id="userService"/>
Or, if you are using a Java based configuration class, you need to add a bean like so:
#Configuration
public class AppConfig{
#Bean
public UserService userService() {
return new UserServiceImpl();
}
}
Or, if you add the #Component annotation to UserServiceImpl and #ComponentScan("service") annotation to the Java App config, it should pick up the User service
Make sure you have enabled the component scanning to automatically detect classes and register respective beans.
You should add below entry to your bean definition XML file:
<context:component-scan base-package="org.example"/>
More about automatic bean detection

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

Resources