问题及背景表述

刚创建了一个小项目
层级大概是这样的

├─.idea
├─Bilibili-api
│  ├─src
│  │  ├─main
│  │  │  ├─java
│  │  │  │  └─com
│  │  │  │      └─xiaosheng
│  │  │  │          └─video
│  │  │  │              └─api
│  │  │  │                  ├─config
│  │  │  │                  ├─controller
│  │  │  │                  ├─request
│  │  │  │                  └─response
│  │  │  └─resources
│  │  └─test
│  │      └─java
│  └─target
│      ├─classes
│      │  └─com
│      │      └─xiaosheng
│      │          └─video
│      │              └─api
│      │                  └─controller
│      └─generated-sources
│          └─annotations
├─Bilibili-dao
│  ├─src
│  │  ├─main
│  │  │  ├─java
│  │  │  │  └─com
│  │  │  │      └─xiaosheng
│  │  │  │          └─video
│  │  │  │              └─dao
│  │  │  │                  ├─mapper
│  │  │  │                  └─po
│  │  │  └─resources
│  │  │      └─mapping
│  │  └─test
│  │      └─java
│  └─target
│      ├─classes
│      │  ├─com
│      │  │  └─xiaosheng
│      │  │      └─video
│      │  │          └─dao
│      │  │              └─mapper
│      │  └─mapping
│      └─generated-sources
│          └─annotations
├─Bilibili-facade
│  ├─src
│  │  ├─main
│  │  │  ├─java
│  │  │  │  └─com
│  │  │  │      └─xiaosheng
│  │  │  │          └─video
│  │  │  │              └─facade
│  │  │  │                  ├─bo
│  │  │  │                  ├─dto
│  │  │  │                  └─enums
│  │  │  └─resources
│  │  └─test
│  │      └─java
│  └─target
│      ├─classes
│      ├─maven-archiver
│      └─maven-status
│          └─maven-compiler-plugin
│              ├─compile
│              │  └─default-compile
│              └─testCompile
│                  └─default-testCompile
└─Bilibili-services
    ├─src
    │  ├─main
    │  │  ├─java
    │  │  │  └─com
    │  │  │      └─xiaosheng
    │  │  │          └─video
    │  │  │              └─services
    │  │  │                  ├─service
    │  │  │                  └─util
    │  │  └─resources
    │  └─test
    │      └─java
    └─target
        ├─classes
        │  └─com
        │      └─xiaosheng
        │          └─video
        │              └─services
        │                  └─service
        └─generated-sources
            └─annotations

代码

启动类

@MapperScan("com.xiaosheng.video.dao.mapper")
@SpringBootApplication
public class BilibiliApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(BilibiliApplication.class, args);
    }
}

service

@Service
public class DemoService {
    @Resource
    private DemoMapper demoMapper;


    public Map<String, Map<String, Object>> demo() {
        Map<String, Object> stringObjectMap1 = demoMapper.queryallData(1);
        Map<String, Object> stringObjectMap2 = demoMapper.queryallData(2);
        Map<String, Object> stringObjectMap3 = demoMapper.queryallData(3);
        HashMap<String, Map<String, Object>> stringMapHashMap = new HashMap<>();
        stringMapHashMap.put("str", stringObjectMap1);
        stringMapHashMap.put("str2", stringObjectMap2);
        stringMapHashMap.put("str3", stringObjectMap3);
        return stringMapHashMap;
    }
}

interface

@Mapper
public interface DemoMapper {
    Map<String, Object> queryallData(Integer id);
}

mapper.xml

<?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="com.xiaosheng.video.dao.mapper.DemoMapper">

    <select id="queryallData" resultType="java.util.Map">
        select * from jdbc_demo where id =#{id}
    </select>
</mapper>

运行结果

点击运行的时候就这样了

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

2022-09-24 14:40:08.345  INFO 24320 --- [           main] c.x.video.api.BilibiliApplication        : Starting BilibiliApplication using Java 1.8.0_112 on LCYITGLB-lipy with PID 24320 (E:\proj\learn\Bilibili\Bilibili-api\target\classes started by CFDL14965 in E:\proj\learn\Bilibili)
2022-09-24 14:40:08.348  INFO 24320 --- [           main] c.x.video.api.BilibiliApplication        : The following profiles are active: test
2022-09-24 14:40:09.110  INFO 24320 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8083 (http)
2022-09-24 14:40:09.118  INFO 24320 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-09-24 14:40:09.119  INFO 24320 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.46]
2022-09-24 14:40:09.119  INFO 24320 --- [           main] o.a.catalina.core.AprLifecycleListener   : Loaded Apache Tomcat Native library [1.2.35] using APR version [1.7.0].
2022-09-24 14:40:09.120  INFO 24320 --- [           main] o.a.catalina.core.AprLifecycleListener   : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2022-09-24 14:40:09.120  INFO 24320 --- [           main] o.a.catalina.core.AprLifecycleListener   : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2022-09-24 14:40:09.122  INFO 24320 --- [           main] o.a.catalina.core.AprLifecycleListener   : OpenSSL successfully initialized [OpenSSL 1.1.1q  5 Jul 2022]
2022-09-24 14:40:09.171  INFO 24320 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-09-24 14:40:09.171  INFO 24320 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 785 ms
2022-09-24 14:40:09.217  WARN 24320 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'demoController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xiaosheng.video.services.service.DemoService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
2022-09-24 14:40:09.219  INFO 24320 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2022-09-24 14:40:09.233  INFO 24320 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-09-24 14:40:09.249 ERROR 24320 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

A component required a bean of type 'com.xiaosheng.video.services.service.DemoService' that could not be found.

Action:

Consider defining a bean of type 'com.xiaosheng.video.services.service.DemoService' in your configuration.

Process finished with exit code 1

求解

在网上找了很久,无非几个解法

  • mapper interface没写@mapper注解

  • 启动类没写@MapperScan("com.xiaosheng.video.dao.mapper")

  • service层没写@service,或者controller没有把service注入

  • 目录层级不对

四个解决方法和我一个不搭边

解决方法

解决方法
在启动类上方添加如下注解

@ComponentScan(basePackages = {"com.xiaosheng"})
@ComponentScan(basePackages = {"com.xiaosheng"})
@MapperScan("com.xiaosheng.video.dao.mapper")
@SpringBootApplication
public class BilibiliApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(BilibiliApplication.class, args);
    }
}

原理

@ComponentScan主要就是定义扫描的路径从中找出标识了需要装配的类自动装配到spring的bean容器中

@Controller@Service@Repository注解,他们中有一个共同的注解@Component,没错@ComponentScan注解默认就会装配标识了@Controller@Service@Repository@Component注解的类到spring容器中

通过includeFilters加入扫描路径下没有以上注解的类加入spring容器

通过excludeFilters过滤出不用加入spring容器的类

分类: java

0 条评论

发表评论

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用*标注

ICP备案号: 辽ICP备20003309号