Spring MVC Hibernate Integration- PageNotFound - 未找到具有 URI [/spring-mvc-hibernate-xml/shop/create] 的 HTTP 请求的映射

Spring MVC Hibernate Integration- PageNotFound - No mapping found for HTTP request with URI [/spring-mvc-hibernate-xml/shop/create]

我正在开发 Spring MVC + Hibernate + JPA 集成 示例。我成功地开发了这个示例并能够启动 index.jsp,但是当我尝试调用另一个 jsp 时,我看到以下错误即将到来..

2016-03-29 11:30:11 DEBUG DispatcherServlet - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/spring-mvc-hibernate-xml/shop/create]
2016-03-29 11:30:11 DEBUG RequestMappingHandlerMapping - Looking up handler method for path /shop/create
2016-03-29 11:30:11 DEBUG RequestMappingHandlerMapping - Did not find handler method for [/shop/create]
2016-03-29 11:30:11 WARN  PageNotFound - No mapping found for HTTP request with URI [/spring-mvc-hibernate-xml/shop/create] in DispatcherServlet with name 'dispatcherServlet'
2016-03-29 11:30:11 DEBUG DispatcherServlet - Successfully completed request

ShopController.java

@Controller
@RequestMapping(value="/shop")
public class ShopController {

    @Autowired
    private ShopService shopService;

    @Autowired
    private ShopValidator shopValidator;

    @InitBinder
    private void initBinder(WebDataBinder binder) {
        binder.setValidator(shopValidator);
    }

    @RequestMapping(value="/create", method=RequestMethod.GET)
    public ModelAndView newShopPage() {
        ModelAndView mav = new ModelAndView("shop-new", "shop", new Shop());
        return mav;
    }

    @RequestMapping(value="/create", method=RequestMethod.POST)
    public ModelAndView createNewShop(@ModelAttribute @Valid Shop shop,
            BindingResult result,
            final RedirectAttributes redirectAttributes) {

        if (result.hasErrors())
            return new ModelAndView("shop-new");

        ModelAndView mav = new ModelAndView();
        String message = "New shop "+shop.getName()+" was successfully created.";

        shopService.create(shop);
        mav.setViewName("redirect:/index.html");

        redirectAttributes.addFlashAttribute("message", message);   
        return mav;     
    }

    @RequestMapping(value="/list", method=RequestMethod.GET)
    public ModelAndView shopListPage() {
        ModelAndView mav = new ModelAndView("shop-list");
        List<Shop> shopList = shopService.findAll();
        mav.addObject("shopList", shopList);
        return mav;
    }

    @RequestMapping(value="/edit/{id}", method=RequestMethod.GET)
    public ModelAndView editShopPage(@PathVariable Integer id) {
        ModelAndView mav = new ModelAndView("shop-edit");
        Shop shop = shopService.findById(id);
        mav.addObject("shop", shop);
        return mav;
    }

    @RequestMapping(value="/edit/{id}", method=RequestMethod.POST)
    public ModelAndView editShop(@ModelAttribute @Valid Shop shop,
            BindingResult result,
            @PathVariable Integer id,
            final RedirectAttributes redirectAttributes) throws ShopNotFound {

        if (result.hasErrors())
            return new ModelAndView("shop-edit");

        ModelAndView mav = new ModelAndView("redirect:/index.html");
        String message = "Shop was successfully updated.";

        shopService.update(shop);

        redirectAttributes.addFlashAttribute("message", message);   
        return mav;
    }

    @RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
    public ModelAndView deleteShop(@PathVariable Integer id,
            final RedirectAttributes redirectAttributes) throws ShopNotFound {

        ModelAndView mav = new ModelAndView("redirect:/index.html");        

        Shop shop = shopService.delete(id);
        String message = "The shop "+shop.getName()+" was successfully deleted.";

        redirectAttributes.addFlashAttribute("message", message);
        return mav;
    }
}

Shop.java

@Entity
@Table(name = "shops")
public class Shop {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    @Column(name = "employees_number")
    private Integer emplNumber;
    // setters and getters
}

ShopRepository.java

public interface ShopRepository extends JpaRepository<Shop, Integer> {

}

ShopService.java

public interface ShopService {

    public Shop create(Shop shop);
    public Shop delete(int id) throws ShopNotFound;
    public List<Shop> findAll();
    public Shop update(Shop shop) throws ShopNotFound;
    public Shop findById(int id);
}

ShopServiceImpl.java

@Service
public class ShopServiceImpl implements ShopService {

    @Resource
    private ShopRepository shopRepository;

    @Override
    @Transactional
    public Shop create(Shop shop) {
        Shop createdShop = shop;
        return shopRepository.save(createdShop);
    }

    @Override
    @Transactional
    public Shop findById(int id) {
        return shopRepository.findOne(id);
    }

    @Override
    @Transactional(rollbackFor=ShopNotFound.class)
    public Shop delete(int id) throws ShopNotFound {
        Shop deletedShop = shopRepository.findOne(id);

        if (deletedShop == null){
            throw new ShopNotFound();
        }
        shopRepository.delete(deletedShop);
        return deletedShop;
    }

    @Override
    @Transactional
    public List<Shop> findAll() {
        return shopRepository.findAll();
    }

    @Override
    @Transactional(rollbackFor=ShopNotFound.class)
    public Shop update(Shop shop) throws ShopNotFound {
        Shop updatedShop = shopRepository.findOne(shop.getId());

        if (updatedShop == null)
            throw new ShopNotFound();

        updatedShop.setName(shop.getName());
        updatedShop.setEmplNumber(shop.getEmplNumber());
        return updatedShop;
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

    <display-name>spr-data</display-name>

    <!-- 
        - Location of the XML file that defines the root application context.
        - Applied by ContextLoaderListener.
    -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/application-config.xml</param-value>
    </context-param>


    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <!--
        - Servlet that dispatches request to registered handlers (Controller implementations).
    -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <welcome-file-list>
         <!-- <welcome-file>redirect.jsp</welcome-file> -->
         <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!-- Disable JSESSIONID -->
    <session-config>
        <session-timeout>1</session-timeout>
        <cookie-config>
            <max-age>0</max-age>
        </cookie-config>
    </session-config>
</web-app>

mvc-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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.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.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

    <mvc:annotation-driven />

    <!-- Enables the Spring MVC @Controller programming model -->
    <mvc:annotation-driven />

    <context:property-placeholder location="classpath:database.properties" />

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!-- DataSource -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${mysql.jdbc.driverClassName}" />
        <property name="url" value="${mysql.jdbc.url}" />
        <property name="username" value="${mysql.jdbc.userName}" />
        <property name="password" value="${mysql.jdbc.password}" />
    </bean>

    <!-- Local Container Entity Manager -->
    <bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />

        <property name="packagesToScan" value="com.spr.*" />

        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>

        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="myEmf" />
    </bean>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>


    <!-- ======= Localization of hibernate messages during validation!  ======= -->
    <bean id="validationMessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
    </bean>

    <bean name="validator"  class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="validationMessageSource">
           <ref bean="validationMessageSource"/>
        </property>
    </bean>
</beans>

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Home page</title>
</head>
<body>
    <h1>Home page</h1>
    <p>
        Welcome to "Shop application".<br /> <i>${message}</i><br /> <a
            href="${pageContext.request.contextPath}/shop/create">Create
            a new shop</a><br /> <a
            href="${pageContext.request.contextPath}/shop/list">View all
            shops</a><br />
    </p>
    <%-- <p>
        Welcome to "Shop application".<br /> <i>${message}</i><br /> <a
            href="${pageContext.request.contextPath}/shop/create.html">Create
            a new shop</a><br /> <a
            href="${pageContext.request.contextPath}/shop/list.html">View all
            shops</a><br />
    </p> --%>
</body>
</html>

店铺-edit.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Edit Shop page</title>
</head>
<body>
<h1>Edit Shop page</h1>
<form:form method="POST" commandName="shop" action="${pageContext.request.contextPath}/shop/edit/${shop.id}.html" >
<table>
<tbody>
<tr>
<td>Shop name:</td>
<td><form:input path="name" /></td>
<td><form:errors path="name" cssStyle="color: red;"/></td>
</tr>
<tr>
<td>Employees number:</td>
<td><form:input path="emplNumber" /></td>
<td><form:errors path="emplNumber" cssStyle="color: red;"/></td>
</tr>
<tr>
<td><input type="submit" value="Create" /></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</form:form>
<a href="${pageContext.request.contextPath}/">Home page</a>
</body>
</html>

店铺-list.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Shop List page</title>
</head>
<body>
<h1>Shop List page</h1>
<table style="text-align: center;" border="1px" cellpadding="0" cellspacing="0" >
<thead>
<tr>
<th width="25px">id</th><th width="150px">company</th><th width="25px">employees</th><th width="50px">actions</th>
</tr>
</thead>
<tbody>
<c:forEach var="shop" items="${shopList}">
<tr>
<td>${shop.id}</td>
<td>${shop.name}</td>
<td>${shop.emplNumber}</td>
<td>
<a href="${pageContext.request.contextPath}/shop/edit/${shop.id}.html">Edit</a><br/>
<a href="${pageContext.request.contextPath}/shop/delete/${shop.id}.html">Delete</a><br/>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<a href="${pageContext.request.contextPath}/">Home page</a>
</body>
</html>

店铺-new.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>New Shop page</title>
</head>
<body>
    <h1>New Shop page</h1>
    <form:form method="POST" commandName="shop"
        action="${pageContext.request.contextPath}/shop/create.html">
        <table>
            <tbody>
                <tr>
                    <td>Shop name:</td>
                    <td><form:input path="name" /></td>
                    <td><form:errors path="name" cssStyle="color: red;" /></td>
                </tr>
                <tr>
                    <td>Employees number:</td>
                    <td><form:input path="emplNumber" /></td>
                    <td><form:errors path="emplNumber" cssStyle="color: red;" /></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Create" /></td>
                    <td></td>
                    <td></td>
                </tr>
            </tbody>
        </table>
    </form:form>
    <a href="${pageContext.request.contextPath}/">Home page</a>
</body>
</html>

请高手指点,这是怎么回事?为什么找不到路径? 附上项目结构:

编辑-1: 现在我面临以下错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shopController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.spr.validation.ShopValidator com.spr.controller.ShopController.shopValidator; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.spr.validation.ShopValidator] 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)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1208) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:303) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762) ~[spring-context-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) ~[spring-context-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:664) ~[spring-webmvc-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:630) ~[spring-webmvc-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:678) ~[spring-webmvc-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:549) ~[spring-webmvc-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:490) ~[spring-webmvc-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) [spring-webmvc-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at javax.servlet.GenericServlet.init(GenericServlet.java:158) [servlet-api.jar:3.1.FR]
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231) [catalina.jar:8.0.30]
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144) [catalina.jar:8.0.30]
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1031) [catalina.jar:8.0.30]
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4997) [catalina.jar:8.0.30]
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5289) [catalina.jar:8.0.30]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:8.0.30]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408) [catalina.jar:8.0.30]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398) [catalina.jar:8.0.30]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_45]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_45]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_45]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_45]
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.spr.validation.ShopValidator com.spr.controller.ShopController.shopValidator; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.spr.validation.ShopValidator] 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)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    ... 29 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.spr.validation.ShopValidator] 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)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) ~[spring-beans-4.1.9.RELEASE.jar:4.1.9.RELEASE]
    ... 31 common frames omitted
Mar 29, 2016 12:13:07 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shopController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.spr.validation.ShopValidator com.spr.controller.ShopController.shopValidator; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.spr.validation.ShopValidator] 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)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1208)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:664)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:630)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:678)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:549)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:490)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1031)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4997)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5289)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.spr.validation.ShopValidator com.spr.controller.ShopController.shopValidator; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.spr.validation.ShopValidator] 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)}

我在我的 mvc 中添加了以下内容-config.xml:

<mvc:annotation-driven />

<context:property-placeholder location="classpath:database.properties" />

<context:component-scan base-package="com.spr.controller" />

<jpa:repositories base-package="com.spr.repository" entity-manager-factory-ref="myEmf" />

<tx:annotation-driven transaction-manager="transactionManager"/>

<bean id="shopService" class="com.spr.service.ShopServiceImpl" />
<bean id="shopValidator" class="com.spr.service.ShopServiceImpl" />

组件扫描器 添加到您的 mvc-config.xml。通过这种方式,您可以告诉 Spring 扫描您的控制器包并实例化并注册您的 处理程序方法 。假设,您的控制器在 com.so.controller 包中,那么您应该将其添加到 mvc-config.xml:

<context:component-scan base-package="com.so.controller" />

此外,您确实在 mvc-config.xml:

中两次启用了注解驱动的 MVC
<mvc:annotation-driven />

<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven />

只保留一个,删除另一个。最后一点,最好为应用程序的每个架构方面定义多个 配置文件 ,例如Web、数据访问、安全等,并且只在它们中的每一个中放置相关的大火。目前,您有一个 mvc-config.xml 配置文件,其中包含与数据访问相关的配置。

您需要进行以下更改。还有阿里的建议很好很正确

您需要在 src/main/java 文件夹中创建 META-INF\persistence.xml 文件。

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="spring-data-jpa-krishna" transaction-type="RESOURCE_LOCAL">
        <class>com.spr.model.Shop</class>
    </persistence-unit>
</persistence>

这些很重要。确保您的配置中没有遗漏任何内容:

<mvc:annotation-driven />

    <context:property-placeholder location="classpath:database.properties" />

    <context:component-scan base-package="com.spr.controller" />

    <jpa:repositories base-package="com.spr.repository" />

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!-- Necessary to get the entity manager injected into the factory bean -->
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

接下来重要的,不要用id=myEmf,下面简单用一下:

<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="showSql" value="true"/>
        <property name="generateDdl" value="true"/>
        <!-- <property name="database" value="MYSQL"/> -->
    </bean>

只需使用这个:

<!-- Local Container Entity Manager -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />

        <property name="packagesToScan" value="com.spr.model" />

        <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>

        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            </props>
        </property>
    </bean>