Я пытаюсь создать проект с использованием Spring MVC и JPA, но у меня возникает проблема при попытке запустить приложение - есть исключение, которое выглядит следующим образом (несколько строк каждого): исключение
javax.servlet.ServletException: Servlet.init() for servlet appServlet threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
основная причина
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0': Initialization of bean failed; nested exception is 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: private com.lovemyway.itlovers.persistence.JpaUserDao com.lovemyway.itlovers.controllers.HomeController.jpaUserDao; nested exception is java.lang.IllegalArgumentException: Can not set com.lovemyway.itlovers.persistence.JpaUserDao field com.lovemyway.itlovers.controllers.HomeController.jpaUserDao to $Proxy33
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
Мой код выглядит следующим образом: JpaUserDao.java
package com.lovemyway.itlovers.persistence;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.lovemyway.itlovers.domain.User;
@Repository("jpaUserDao")
@Transactional
public class JpaUserDao implements UserDao {
@PersistenceContext
private EntityManager em;
public void addUser(User user) {
em.persist(user);
}
public void removeUser(User user) {
em.remove(user);
}
public User findUserById(int id) {
return em.find(User.class, id);
}
}
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.lovemyway.itlovers" />
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="persistenceUnitName" value="ITlovers"/>
</beans:bean>
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/itlovers" />
<property name="username" value="root" />
<property name="password" value="root" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</beans:bean>
<beans:bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="true"/>
<property name="generateDdl" value="false"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
</beans:bean>
<beans:bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</beans:bean>
<beans:bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<beans:bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
ИКонтроллер, вызывающий исключение:
HomeController.java
package com.lovemyway.itlovers.controllers;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.lovemyway.itlovers.domain.Rank;
import com.lovemyway.itlovers.domain.User;
import com.lovemyway.itlovers.persistence.JpaUserDao;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@Autowired
private JpaUserDao jpaUserDao;
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! the client locale is "+ locale.toString());
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
Rank r = new Rank();
r.setColor("aa");
r.setDescription("a4aa");
r.setName("ranga");
User u = new User();
u.setActive(true);
u.setAdmin(true);
u.setUsername("szaku2");
u.setEmail("aaa");
u.setPassword("aaa");
u.setRegistrationDate(date);
u.setLastLoginDate(date);
u.setRank(r);
jpaUserDao.addUser(u);
jpaUserDao.findUserById(2);
model.addAttribute("serverTime", formattedDate);
return "home";
}
}
Что я делаю не так?Меня смущает слишком много XML-файлов. Если я создаю экземпляр jpaUserDao, используя новый конструктор (я думаю, я аннотировал его @Repository, чтобы не делать этого), я получаю исключение NullPointerException.
С уважением, Марчин