您好,登錄后才能下訂單哦!
如何理解@Resource注入失敗問題,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
項目結構
front和client是兩個不同的服務,front依賴client項目,需要在front中注入client的類
聲明類:
import com.bluewhale.infra.client.IRestClient; ... ... @Component("defaultWebServiceRequestHandler") public class DefaultWebServiceRequestHandler implements BaseHandler { protected Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource(name = "seckillClient") private IRestClient seckillClient; @Resource(name = "objectMapper") protected ObjectMapper objectMapper; @Resource(name = "restMapping") public Map<String, String> restMapping; ... ... }
注解類:
import org.springframework.stereotype.Component; import com.bluewhale.infra.client.IRestClient; import com.bluewhale.infra.client.impl.BaseRestClient; @Component("seckillClient") public class SeckillClient extends BaseRestClient implements IRestClient { @Override protected String getServerUrl() { return "http://etrade-trans-web/json/"; } }
seckillClent實現了IRestClient接口,在DefaultWebServiceRequestHandler 中注入IRestClient,通過@Resource注解找到對應的類。
但在啟動front服務器報錯
從報錯日志可以看出是因為找不到名為“seckillClient”的依賴,注入失敗。
從代碼中來看,完全可以確定所有配置正常,注解正常
2019-08-19 11:00:59.105 INFO 7376 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@31c7528f: startup date [Mon Aug 19 11:00:59 CST 2019]; root of context hierarchy 2019-08-19 11:00:59.294 INFO 7376 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring 2019-08-19 11:00:59.326 INFO 7376 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$ddfb45d6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.9.RELEASE) 2019-08-19 11:00:59.778 INFO 7376 --- [ main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at: http://localhost:8888 2019-08-19 11:01:00.856 WARN 7376 --- [ main] c.c.c.ConfigServicePropertySourceLocator : Could not locate PropertySource: I/O error on GET request for "http://localhost:8888/bluewhale-seckill-front/default": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect 2019-08-19 11:01:00.856 INFO 7376 --- [ main] bluewhale.front.FrontApplication : No active profile set, falling back to default profiles: default 2019-08-19 11:01:00.903 INFO 7376 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5e4fa1da: startup date [Mon Aug 19 11:01:00 CST 2019]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@31c7528f 2019-08-19 11:01:01.825 INFO 7376 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=34349be5-556c-35e3-8c99-3121c02e2e06 2019-08-19 11:01:01.840 INFO 7376 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring 2019-08-19 11:01:01.950 INFO 7376 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.netflix.metrics.MetricsInterceptorConfiguration$MetricsRestTemplateConfiguration' of type [org.springframework.cloud.netflix.metrics.MetricsInterceptorConfiguration$MetricsRestTemplateConfiguration$$EnhancerBySpringCGLIB$$f40de91a] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2019-08-19 11:01:02.013 INFO 7376 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$ddfb45d6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2019-08-19 11:01:02.231 INFO 7376 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 11002 (http) 2019-08-19 11:01:02.247 INFO 7376 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2019-08-19 11:01:02.247 INFO 7376 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.23 2019-08-19 11:01:02.372 INFO 7376 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2019-08-19 11:01:02.372 INFO 7376 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1469 ms 2019-08-19 11:01:02.559 INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2019-08-19 11:01:02.575 INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'metricsFilter' to: [/*] 2019-08-19 11:01:02.575 INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2019-08-19 11:01:02.575 INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2019-08-19 11:01:02.575 INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2019-08-19 11:01:02.575 INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2019-08-19 11:01:02.575 INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'webRequestLoggingFilter' to: [/*] 2019-08-19 11:01:02.575 INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'applicationContextIdFilter' to: [/*] 2019-08-19 11:01:02.685 WARN 7376 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '/front': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'frontExecuter': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'frontProcessFactory': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'frontProcessConfig': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'logoutProcess': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'frontHandlerConfig': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultWebServiceRequestHandler': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'seckillClient' available 2019-08-19 11:01:02.685 INFO 7376 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2019-08-19 11:01:02.700 INFO 7376 --- [ main] utoConfigurationReportLoggingInitializer : Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled. 2019-08-19 11:01:02.794 ERROR 7376 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: A component required a bean named 'seckillClient' that could not be found. Action: Consider defining a bean named 'seckillClient' in your configuration.
經過排查及網上查詢發現問題所在
因為項目有做業務分離,所以在啟動front服務器,加載主程序時SpringBoot會對依賴包進行掃描,因此需要在主程序入口指定掃描的位置,否則有的地方可能會注入失敗。
所以需要在front的Application中指定掃描的包
package bluewhale.front; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages = { "com.bluewhale.infra", "etrade" }) @EnableDiscoveryClient @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) public class FrontApplication { public static void main(String[] args) throws Exception { SpringApplication.run(FrontApplication.class, args); } }
如果你的其他包層次結構位于使用@SpringBootApplication標注主應用程序下方,則隱式組件掃描將自動涵蓋。也就是說,不要明確標注@ComponentScan,Spring Boot會自動搜索當前應用主入口目錄及其下方子目錄。
如果其他包中的bean /組件不在當前主包路徑下面,,則應手動使用@ComponentScan 添加
如果使用了@ComponentScan ,那么Spring Boot就全部依賴你的定義,如果定義出錯,會出現autowired時出錯,報a bean of type that could not be found錯誤
看完上述內容,你們掌握如何理解@Resource注入失敗問題的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。