溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何理解@Resource注入失敗問(wèn)題

發(fā)布時(shí)間:2021-10-20 10:19:26 來(lái)源:億速云 閱讀:334 作者:柒染 欄目:大數(shù)據(jù)

如何理解@Resource注入失敗問(wèn)題,相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。

項(xiàng)目結(jié)構(gòu)

如何理解@Resource注入失敗問(wèn)題

front和client是兩個(gè)不同的服務(wù),front依賴(lài)client項(xiàng)目,需要在front中注入client的類(lèi)

聲明類(lèi):

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;
    
    ... ...

}

注解類(lèi):

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實(shí)現(xiàn)了IRestClient接口,在DefaultWebServiceRequestHandler 中注入IRestClient,通過(guò)@Resource注解找到對(duì)應(yīng)的類(lèi)。

但在啟動(dòng)front服務(wù)器報(bào)錯(cuò)

從報(bào)錯(cuò)日志可以看出是因?yàn)檎也坏矫麨椤皊eckillClient”的依賴(lài),注入失敗。

從代碼中來(lái)看,完全可以確定所有配置正常,注解正常

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.

經(jīng)過(guò)排查及網(wǎng)上查詢(xún)發(fā)現(xiàn)問(wèn)題所在

因?yàn)轫?xiàng)目有做業(yè)務(wù)分離,所以在啟動(dòng)front服務(wù)器,加載主程序時(shí)SpringBoot會(huì)對(duì)依賴(lài)包進(jìn)行掃描,因此需要在主程序入口指定掃描的位置,否則有的地方可能會(huì)注入失敗。

所以需要在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);
	}
}

Spring Boot項(xiàng)目中的組件掃描

  • 如果你的其他包層次結(jié)構(gòu)位于使用@SpringBootApplication標(biāo)注主應(yīng)用程序下方,則隱式組件掃描將自動(dòng)涵蓋。也就是說(shuō),不要明確標(biāo)注@ComponentScan,Spring Boot會(huì)自動(dòng)搜索當(dāng)前應(yīng)用主入口目錄及其下方子目錄。

  • 如果其他包中的bean /組件不在當(dāng)前主包路徑下面,,則應(yīng)手動(dòng)使用@ComponentScan 添加

  • 如果使用了@ComponentScan ,那么Spring Boot就全部依賴(lài)你的定義,如果定義出錯(cuò),會(huì)出現(xiàn)autowired時(shí)出錯(cuò),報(bào)a bean of type that could not be found錯(cuò)誤

看完上述內(nèi)容,你們掌握如何理解@Resource注入失敗問(wèn)題的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI