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