springboot 無法掃描到父類模塊中Bean的原因及解決
springboot 無法掃描到父類模塊中Bean
現(xiàn)象:
我定義了兩個(gè)模塊 A 和 B 。B模塊依賴A模塊
A模塊中我定義了一個(gè)@Component
卻發(fā)現(xiàn)在B模塊中我無法掃描到這個(gè)Bean導(dǎo)入注入失敗
如何解決
查閱得知,在springboot中的bean掃描是掃描同級目錄或者下級目錄,也就是不會掃描到依賴包里面的東西。
但是我又想定義公共Bean,該怎么做呢。
解決方案
手動注入 @Bean
如果你定義的是實(shí)體類之類的Bean,那么可以在子類中手動Bean
@Bean
Result result(){
new Result;
}
配置掃描 @ComponentScan
但是如果你定義的Bean是類似于接口的文件,那你使用手動定義的方法就會發(fā)現(xiàn)要寫很長一段,把所有的方法都定義一下。所以還有另一種方法
@SpringBootApplication
@ComponentScan(basePackages = {"cn.o"})
public class ProxyDataSourceApplication {
...main(){
}
}
如果定義了@ComponentScan掃描路徑,注意不要讓@Bean多處定義,否則會報(bào)重復(fù)注入的錯(cuò)誤。
spring boot 啟動就自動關(guān)閉 之 找不到bean
創(chuàng)建的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);
}
}
控制臺報(bào)錯(cuò):
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,沒有注入進(jìn)去。
解決方法:
@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識別,問題的核心關(guān)鍵就在application類的注解SpringBootApplication上
這個(gè)注解其實(shí)相當(dāng)于下面這一堆注解的效果,其中一個(gè)注解就是@Component,在默認(rèn)情況下只能掃描與控制器在同一個(gè)包下以及其子包下的@Component注解,以及能將指定注解的類自動注冊為Bean的@Service@Controller和@ Repository,至此明白問題所在,之前我將接口與對應(yīng)實(shí)現(xiàn)類放在了與控制器所在包的同一級目錄下,這樣的注解自然是無法被識別的
所以有兩種解決辦法:
1 .將接口與對應(yīng)的實(shí)現(xiàn)類放在與application啟動類的同一個(gè)目錄或者他的子目錄下,這樣注解可以被掃描到,這是最省事的辦法
2 .在指定的application類上加上這么一行注解,手動指定application類要掃描哪些包下的注解。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
springboot tomcat的maxHttpFormPostSize參數(shù)示例解析
這篇文章主要介紹了springboot tomcat的maxHttpFormPostSize參數(shù)示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
Java數(shù)據(jù)類型Integer與int的區(qū)別詳細(xì)解析
這篇文章主要介紹了Java數(shù)據(jù)類型Integer與int的區(qū)別詳細(xì)解析,Ingeter是int的包裝類,int的初值為0,Ingeter的初值為null,int和integer(無論new否)比,都為true,因?yàn)闀袸nteger自動拆箱為int再去比,需要的朋友可以參考下2023-12-12
使用redis的increment()方法實(shí)現(xiàn)計(jì)數(shù)器功能案例
這篇文章主要介紹了使用redis的increment()方法實(shí)現(xiàn)計(jì)數(shù)器功能案例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
Java中Queue的poll()和remove()區(qū)別詳解
這篇文章主要介紹了Java中Queue的poll()和remove()區(qū)別詳解,Queue接口提供了許多方法,其中poll()和remove()是兩個(gè)常用的方法,它們的區(qū)別在于,當(dāng)隊(duì)列為空時(shí),poll()方法返回null,而remove()方法會拋出,需要的朋友可以參考下2023-07-07
JDK常用命令jps jinfo jstat的具體說明與示例
JDK本身提供了很多方便的JVM性能調(diào)優(yōu)監(jiān)控工具,除了集成式的VisualVM和jConsole外,還有jps、jinfo、jstat等小巧的工具,本文章希望能起拋磚引玉之用,讓大家能開始對JVM性能調(diào)優(yōu)的常用工具有所了解2021-09-09
Spring Security保護(hù)用戶密碼常用方法詳解
這篇文章主要介紹了Spring Security保護(hù)用戶密碼常用方法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09
Java?spring?boot實(shí)現(xiàn)批量刪除功能詳細(xì)示例
這篇文章主要給大家介紹了關(guān)于Java?spring?boot實(shí)現(xiàn)批量刪除功能的相關(guān)資料,文中通過代碼以及圖文將實(shí)現(xiàn)的方法介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2023-08-08

