十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
如何理解@Resource注入失败问题,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
兴县网站制作公司哪家好,找成都创新互联!从网页设计、网站建设、微信开发、APP开发、成都响应式网站建设公司等网站项目制作,到程序开发,运营维护。成都创新互联从2013年成立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选成都创新互联。
项目结构
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 MaprestMapping; ... ... }
注解类:
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注入失败问题的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!