springboot 无法扫描到父类模块中Bean的原因及解决

目录
  • springboot 无法扫描到父类模块中Bean
    • 现象:
    • 如何解决
    • 解决方案
  • spring boot 启动就自动关闭 之 找不到bean
    • 解决方法:
    • 原因:
    • 以下收集别的解释:
    • 所以有两种解决办法:

springboot 无法扫描到父类模块中Bean

现象:

我定义了两个模块 A 和 B 。B模块依赖A模块

A模块中我定义了一个@Component

却发现在B模块中我无法扫描到这个Bean导入注入失败

如何解决

查阅得知,在springboot中的bean扫描是扫描同级目录或者下级目录,也就是不会扫描到依赖包里面的东西。

但是我又想定义公共Bean,该怎么做呢。

解决方案

手动注入 @Bean

如果你定义的是实体类之类的Bean,那么可以在子类中手动Bean

@Bean
Result result(){
 new Result;
}

配置扫描 @ComponentScan

但是如果你定义的Bean是类似于接口的文件,那你使用手动定义的方法就会发现要写很长一段,把所有的方法都定义一下。所以还有另一种方法

@SpringBootApplication
@ComponentScan(basePackages = {"cn.o"})
public class ProxyDataSourceApplication {
 ...main(){
 }
}

如果定义了@ComponentScan扫描路径,注意不要让@Bean多处定义,否则会报重复注入的错误。

spring boot 启动就自动关闭 之 找不到bean

创建的bean

package com.springboot.entity;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

/**
 * Created by ASUS on 2018/3/20.
 */
@Component
@ConfigurationProperties(prefix = "author")
public class AuthorBean {
    private String name;
    private Long age;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setAge(Long age) {
        this.age = age;
    }

    public Long getAge() {
        return age;
    }
}

写的application类

package com.springboot.demo;
import com.springboot.entity.AuthorBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by ASUS on 2018/3/20.
 */
@RestController
@org.springframework.boot.autoconfigure.SpringBootApplication

public class ApplicationDemo {
    @Autowired
    private AuthorBean authorBean;

    @RequestMapping("/kkk")
    String index(){
        return "author name ="+authorBean.getName()+"author age="+authorBean.getAge();
    }

    public static void main(String[] args) {
        SpringApplication.run(ApplicationDemo.class,args);
    }
}

控制台报错:

2018-03-20 22:22:02.070 INFO 11360 --- [ main] com.springboot.demo.ApplicationDemo : Starting ApplicationDemo on DESKTOP-IV2AEJK with PID 11360 (D:\IDEA\IDEAWorkSpace\SpringBootDemo\target\classes started by ASUS in D:\IDEA\IDEAWorkSpace\SpringBootDemo)
2018-03-20 22:22:02.074 INFO 11360 --- [ main] com.springboot.demo.ApplicationDemo : No active profile set, falling back to default profiles: default
2018-03-20 22:22:02.144 INFO 11360 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3fa980b: startup date [Tue Mar 20 22:22:02 CST 2018]; root of context hierarchy
2018-03-20 22:22:03.453 INFO 11360 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 9090 (http)
2018-03-20 22:22:03.462 INFO 11360 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-03-20 22:22:03.463 INFO 11360 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.27
2018-03-20 22:22:03.557 INFO 11360 --- [ost-startStop-1] o.a.c.c.C.[.[localhost].[/helloboot] : Initializing Spring embedded WebApplicationContext
2018-03-20 22:22:03.558 INFO 11360 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1416 ms
2018-03-20 22:22:03.704 INFO 11360 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-03-20 22:22:03.707 INFO 11360 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-03-20 22:22:03.707 INFO 11360 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-03-20 22:22:03.707 INFO 11360 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-03-20 22:22:03.708 INFO 11360 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-03-20 22:22:03.741 WARN 11360 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationDemo': Unsatisfied dependency expressed through field 'authorBean'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.springboot.entity.AuthorBean' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2018-03-20 22:22:03.742 INFO 11360 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-03-20 22:22:03.761 INFO 11360 --- [ main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-03-20 22:22:03.858 ERROR 11360 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :

***************************
APPLICATION FAILED TO START
***************************
Description:
Field authorBean in com.springboot.demo.ApplicationDemo required a bean of type 'com.springboot.entity.AuthorBean' that could not be found.
Action:
Consider defining a bean of type 'com.springboot.entity.AuthorBean' in your configuration.
Process finished with exit code 1

其中:

意思就是找不到bean,没有注入进去。

解决方法:

@RestController
@org.springframework.boot.autoconfigure.SpringBootApplication
@ComponentScan(basePackages = {"com.springboot.entity"})
public class ApplicationDemo {
    @Autowired
    private AuthorBean authorBean;

加注解

@ComponentScan(basePackages = {"com.springboot.entity"})

原因:

@SpringBootApplication 注解组合了@Configuration @EnableAutoConfiguration,@ComponentScan.

spring boot 会自动扫描@SpringBootApplication 所在类的同级包以及下级包里的Bean ,建议入口类放置在groupid+arctifactId 组合的包名下

以下收集别的解释:

正常情况下加上@Component注解的类会自动被Spring扫描到生成Bean注册到spring容器中,既然他说没找到,也就是该注解被没有被spring识别,问题的核心关键就在application类的注解SpringBootApplication上

这个注解其实相当于下面这一堆注解的效果,其中一个注解就是@Component,在默认情况下只能扫描与控制器在同一个包下以及其子包下的@Component注解,以及能将指定注解的类自动注册为Bean的@Service@Controller和@ Repository,至此明白问题所在,之前我将接口与对应实现类放在了与控制器所在包的同一级目录下,这样的注解自然是无法被识别的

所以有两种解决办法:

1 .将接口与对应的实现类放在与application启动类的同一个目录或者他的子目录下,这样注解可以被扫描到,这是最省事的办法

2 .在指定的application类上加上这么一行注解,手动指定application类要扫描哪些包下的注解。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 详解Spring Boot应用的启动和停止(start启动)

    Spring Boot,作为Spring框架对"约定优先于配置(Convention Over Configuration)"理念的最佳实践的产物,它能帮助我们很快捷的创建出独立运行.产品级别的基于Spring框架的应用,大部分Spring Boot应用只需要非常少的配置就可以快速运行起来,是一个与微服务(MicroServices)相当契合的微框架. 下面主要有两种方式进行Spring Boot的关闭:通过HTTP发送shutdown信号,或者通过service stop的方式. 一

  • Spring自动扫描无法扫描jar包中bean的解决方法

    发现问题 前几天用eclipse打包了一个jar包,jar包里面是定义的Spring的bean. 然后将jar包放到lib下,设置spring的自动扫描这个jar包中的bean,可谁知根本无法扫描到bean,显示错误就是找不到bean,当时就纳闷儿了,为什么扫描不到,结果搜索之后才发现,用eclipse打包jar包要勾选"Add directory entries"才能被Spring正确扫描到,居然有这个说法,呵呵- 不知道 勾选"Add directory entries&

  • Springboot测试类没有bean注入问题解析

    这篇文章主要介绍了Springboot测试类没有bean注入问题解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 其他乱七八糟配置就不扯了,先上项目结构图 配置好参数后我再src/test/java类测试访问数据库时发现bean没有正确的注入.值得注意的是,这个项目的启动类是叫App.java 所以我们必须在这个测试类上面加上注解: @RunWith(SpringRunner.class) @SpringBootTest(classes =

  • 详解springBoot启动时找不到或无法加载主类解决办法

    1.jar包错误 第一步:首先鼠标键右击你的项目,点击run as-->maven clean 第二步:鼠标键右击你的项目,run as--->maven install:在eclipse控制台你可以看见报错的jar包: 第三步:去maven仓库删除对应的jar,右击你的项目,maven-->update project(重新下载jar包): 第四步:重复一,二步骤,找到你的启动类,run as java application;问题解决 2.jdk报错 打开你的项目结构,找到libra

  • 解决Spring Boot 多模块注入访问不到jar包中的Bean问题

    情景描述 一个聚合项目spring-security-tutorial,其中包括4个module,pom如下所示: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://mav

  • springboot 无法扫描到父类模块中Bean的原因及解决

    目录 springboot 无法扫描到父类模块中Bean 现象: 如何解决 解决方案 spring boot 启动就自动关闭 之 找不到bean 解决方法: 原因: 以下收集别的解释: 所以有两种解决办法: springboot 无法扫描到父类模块中Bean 现象: 我定义了两个模块 A 和 B .B模块依赖A模块 A模块中我定义了一个@Component 却发现在B模块中我无法扫描到这个Bean导入注入失败 如何解决 查阅得知,在springboot中的bean扫描是扫描同级目录或者下级目录,

  • SpringBoot普通类获取spring容器中bean的操作

    前言 在spring框架中,是无法在普通类中通过注解注入实例的,因为sping框架在启动的时候,就会将标明交给spring容器管理的类进行实例化,并梳理他们彼此的依赖关系,进行注入,没有交给spring容器管理的普通类,是不会进行注入的,即使你使用了注入的相关注解.这个时候,如果我们需要在普通类中获取spring容器中的实例,就需要一些特定的方法,这里将整理一下如何在springboot中实现这样的方法. 创建springboot工程demo 项目结构图示 项目结构说明 service包下为de

  • 浅谈vue在html中出现{{}}的原因及解决方式

    原因: 浏览器渲染机制,解析html结构 -> 加载外部脚本和样式表文件 -> 解析并执行脚本代码 -> 构造html dom模型 -> 加载图片等外部文件 -> 页面加载完毕. 初始化vue的js写在页面底部,也就是最后才执行js脚本. 所以页面从头到尾开始渲染时,渲染到标签时,由于vue还未初始化,所以就会显示类似这样的代码 <h2>{{courseName}}</h2> 当网速很慢的时候就看得比较清楚,可能会让用户误以为bug之类的,快一点的话就

  • SpringBoot启动自动终止也不报错的原因及解决

    目录 SpringBoot启动自动终止也不报错 原因 解决方案 springboot 启动一段时间之后自动挂掉的解决 解决办法 SpringBoot启动自动终止也不报错 Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled. Disconnected from the target VM, address: '

  • @Autowired注解在抽象类中失效的原因及解决

    @Autowired注解在抽象类中失效 最近在工作中遇到这个问题,在抽象类中使用Autowired这个注解,注入mybatis的dao时,总是出现空指针异常,通过日志的打印,发现是这个dao注入失败为空.然后通过new出spring上下文对象,再去调用getBean()方法,获取到这个注入的dao,这样是可行的,但是总是觉得这不是最佳实践,一定有比这个更加优雅的方式能解决这个问题. 我们来还原一下这个问题: 1.定义一个抽象类 声明为spring组件,在其中自动装配另一个bean: @Compo

  • js放到head中失效的原因与解决方法

    1.今天写js碰到一个奇怪的问题,写好的js放到body里面执行,但是放到head中没有任何效果,为什么导致这种原因呢? 看失效代码: <!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/

  • Spring中Bean的加载与SpringBoot的初始化流程详解

    目录 前言 第一章 Spring中Bean的一些简单概念 1.1 SpingIOC简介 1.2 BeanFactory 1.2.1 BeanDefinition 1.2.2 BeanDefinitionRegistry 1.2.3 BeanFactory结构图 1.3 ApplicationContext 第二章 SpringBoot的初始化流程 2.1 准备阶段 2.2 运行阶段 2.2.1 监听器分析 2.2.2 refreshContext 2.3 总结 前言 一直对它们之间的关系感到好奇

  • SpringBoot借助spring.factories文件跨模块实例化Bean

    目录 1. 前言 2. 配置 3. 原理 4. 总结 1. 前言 SpringBoot在包扫描时,并不会扫描子模块下的内容,这样就使得我们的子模块中的Bean无法注入到Spring容器中.SpringBoot就为我们提供了spring.factories这个文件,让我们可以轻松的将子模块的Bean注入到我们的Spring容器中,本篇文章我们就一起探究一下spring.factories 跨模块实例化Bean的原理. 我们在上篇文章中也讲到构建自己构建starter,其中spring.factor

  • 关于SpringBoot拦截器中Bean无法注入的问题

    问题 这两天遇到SpringBoot拦截器中Bean无法注入问题.下面介绍我的思考过程和解决过程: 1.由于其他bean在service,controller层注入一点问题也没有,开始根本没意识到Bean无法注入是在拦截器中无效的问题,一直在查找注解指定的包在哪里配置的,然而却找不到配置,Springboot是用java类的形式加载配置的.在网络的某个角落看到这样的说法: SpringBoot项目的Bean装配默认规则是根据Application类所在的包位置从上往下扫描! "Applicati

  • 详解SpringBoot如何删除引用jar包中的无用bean

    目录 前言 代码示例 实现代码示例 前言 公司有个项目,时间比较赶,而且项目的部分需求,和之前做的项目部分功能一样,为了赶速度和直接将之前多模块的maven项目中的部分模块,直接以jar包的形式引入到新项目中了,虽然省去了不少开发时间,但是造成项目需要导入引入项目jar的相关依赖,导致项目臃肿,启动很慢.有没有办法让项目只加载自己需要的bean呢? 当然我们可以直接修改源代码重新打包引入去解决,但是这个办法太多麻烦. 通过百度的手段,查询可以在springboot启动类上用@ComponentS

随机推荐