Spring 引导控制器需要找不到类型为 'org.dozer.Mapper' 的 bean

Spring Boot controller required a bean of type 'org.dozer.Mapper' that could not be found

我创建了一个 spring 引导项目并添加了

compile('net.sf.dozer:dozer:5.5.1')

依赖关系。但是 class、org.dozer.Mapper 无法被我的应用程序识别。

我 运行 gradle cleangradle buildDependentsgradle build。 但是事情并没有改变。

我该怎么办?

我的build.gradle

buildscript {
    ext {
        springBootVersion = '2.0.0.RC1'
    }
    repositories {
        mavenCentral()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.everglowtrading'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://repo.spring.io/milestone" }
    maven { url "https://repository.jboss.org/nexus/content/repositories/releases" }
}


dependencies {
    compile('org.springframework.boot:spring-boot-starter-aop')
    compile('org.flywaydb:flyway-core')
    compile('org.springframework.boot:spring-boot-starter-hateoas')
    compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.1')
    compile('org.springframework.boot:spring-boot-starter-thymeleaf')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.boot:spring-boot-starter-webflux')
    compile('org.springframework.data:spring-data-commons')
    compile('com.h2database:h2')
    compile('net.sf.dozer:dozer:5.5.1') 
    runtime('org.springframework.boot:spring-boot-devtools')
    runtime('com.h2database:h2')
    compileOnly('org.projectlombok:lombok')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('io.projectreactor:reactor-test')
}

控制器

    package com.myproject.stock.controllers;

    import java.io.IOException;
    import java.util.List;
    import java.util.Locale;

    import javax.servlet.http.HttpServletResponse;

    import org.dozer.Mapper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.MessageSource;
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.Pageable;
    import org.springframework.ui.Model;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.servlet.ModelAndView;

    import com.myproject.stock.domain.model.Stock;
    import com.myproject.stock.domain.repository.StockCriteria;
    import com.myproject.stock.form.StockListForm;
    import com.myproject.stock.service.StockService;

    @RestController
    public class StockController {

        private static final int DEFAULT_PAGEABLE_SIZE = 5;

        @Autowired
        Mapper beanMapper;

        @Autowired
        StockService<Integer> stockService;

        @Autowired 
        MessageSource msg;

        @RequestMapping("/")
        void index(HttpServletResponse response) throws IOException {
            response.sendRedirect("/stock");
        }

        @RequestMapping("/stock")
        public ModelAndView stock(ModelAndView mav) {
            Stock stock = stockService.getItems(11);
            List<Stock> stockList = stockService.getAllItems();
            String message = msg.getMessage("stock.label", null, Locale.JAPAN);
            mav.addObject("stock_id", stock.getId());
            mav.addObject("stockList", stockList);
            mav.addObject("message", message);
            mav.addObject("stockBuildingName", stock.getBuilding_name());
            mav.setViewName("stock/search/index");
            return mav;
        }

        @RequestMapping("/stock/search")
        public String index(@Validated StockListForm stockListForm
                , BindingResult bindingResult
                , Pageable pageable
                , Model model) {

                StockCriteria criteria = beanMapper.map(stockListForm, StockCriteria.class);

            Page<Stock> page = stockService.findPageByCriteria(criteria, pageable);

            model.addAttribute("page", page);

            return "stock/search/index";
        }

    }

错误信息

    .   ____          _            __ _ _
    /\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
    \/  ___)| |_)| | | | | || (_| |  ) ) ) )
    '  |____| .__|_| |_|_| |_\__, | / / / /
    =========|_|==============|___/=/_/_/_/
    :: Spring Boot ::            (v2.0.0.RC1)

    2018-02-19 22:15:35.648  INFO 7950 --- [  restartedMain] c.e.wms.stock.WmsApplication             : Starting WmsApplication on YatabeMBP.local with PID 7950 (/Users/ayatabe/dev/wms-stock/build/classes/java/main started by ayatabe in /Users/ayatabe/dev/wms-stock)
    2018-02-19 22:15:35.648  INFO 7950 --- [  restartedMain] c.e.wms.stock.WmsApplication             : No active profile set, falling back to default profiles: default
    2018-02-19 22:15:35.695  INFO 7950 --- [  restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@82f0a7d: startup date [Mon Feb 19 22:15:35 JST 2018]; root of context hierarchy
    2018-02-19 22:15:36.772  INFO 7950 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d86c709b] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
    2018-02-19 22:15:37.104  INFO 7950 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 9090 (http)
    2018-02-19 22:15:37.114  INFO 7950 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2018-02-19 22:15:37.114  INFO 7950 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.27
    2018-02-19 22:15:37.127  INFO 7950 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/ayatabe/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
    2018-02-19 22:15:37.209  INFO 7950 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2018-02-19 22:15:37.209  INFO 7950 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1517 ms
    2018-02-19 22:15:37.369  INFO 7950 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
    2018-02-19 22:15:37.371  INFO 7950 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet webServlet mapped to [/h2console/*]
    2018-02-19 22:15:37.374  INFO 7950 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
    2018-02-19 22:15:37.374  INFO 7950 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
    2018-02-19 22:15:37.374  INFO 7950 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
    2018-02-19 22:15:37.374  INFO 7950 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
    2018-02-19 22:15:37.415  WARN 7950 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stockController': Unsatisfied dependency expressed through field 'beanMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.dozer.Mapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    2018-02-19 22:15:37.417  INFO 7950 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
    2018-02-19 22:15:37.434  INFO 7950 --- [  restartedMain] ConditionEvaluationReportLoggingListener :

    Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2018-02-19 22:15:37.550 ERROR 7950 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   :

    ***************************
    APPLICATION FAILED TO START
    ***************************

    Description:

    Field beanMapper in com.myproject.stock.controllers.StockController required a bean of type 'org.dozer.Mapper' that could not be found.


    Action:

    Consider defining a bean of type 'org.dozer.Mapper' in your configuration.

您还没有为 org.dozer.Mapper 类型定义 bean,因此 Spring 无法向您的控制器注入正确的实例 class。

定义此 bean 的最简单方法是将以下方法添加到主 Spring 应用程序 class:

@Bean
public Mapper mapper() {
    return new DozerBeanMapper();
}

或者你可以把它放在任何 @Configuration 注释 class.

对于可能 运行 遇到与我相同问题的人:
在 spring 引导主启动 class 中添加 @MapperScan("yourMapperPath")。如果符号显示为红色,请重新导入您的 mybatis-spring-boot-starter 依赖项:

转到您的项目 pom.xml > 右键单击​​ artifactId > Maven > 重新导入

我以为我几天前就导入了依赖项,但项目没有。