亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

拋出 NoSuchBeanDefinitionException

拋出 NoSuchBeanDefinitionException

慕神8447489 2023-09-20 15:30:15
所以我嘗試使用在另一個類中生成的 bean 以在主應用程序中使用    package com.simon.spring.basics.properties;    import org.springframework.beans.factory.annotation.Qualifier;    import org.springframework.beans.factory.annotation.Value;    import org.springframework.stereotype.Component;    @Component    public class SomeExternalService {        @Value("${external.service.url}")        private String url;        public String returnServiceURL(){            return url;        }    }主要應用程序在這里:    package com.simon.spring.basics.springin5steps;    import com.simon.spring.basics.properties.SomeExternalService;    import org.springframework.boot.SpringApplication;    import org.springframework.boot.autoconfigure.SpringBootApplication;    import org.springframework.context.ApplicationContext;    import org.springframework.context.annotation.ComponentScan;    import org.springframework.context.annotation.Configuration;    import org.springframework.context.annotation.PropertySource;@Configuration    @SpringBootApplication    //@PropertySource("classpath:application.properties")    @ComponentScan()    public class SpringIn5StepsPropertiesApplication {        public static void main(String[] args) {            ApplicationContext applicationContext =                    SpringApplication.run(SpringIn5StepsPropertiesApplication.class, args);            SomeExternalService service = applicationContext.getBean(SomeExternalService.class);            System.out.println(service);    }}所以基本上線程“main”org.springframework.beans.factory.NoSuchBeanDefinitionException中的異常:沒有拋出類型為“com.simon.spring.basics.properties.SomeExternalService”的合格bean。我可以做什么來修復此錯誤并避免以后出現同樣的問題
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA貢獻1818條經驗 獲得超3個贊

放入SpringIn5StepsPropertiesApplication你的包根目錄;

package com.simon.spring.basics

也刪除不必要的@ComponentScan()


@SpringBootApplication將自動觸發從主類位置(即 )下的所有包下的組件掃描,以便可以拾取com.simon.spring.basics您的組件。com.simon.spring.basics.properties

否則它會嘗試查找下面的beancom.simon.spring.basics.springin5steps但找不到SomeExternalService


如果移動主類不是一個選項,那么您可以添加其他包,例如;

@SpringBootApplication(scanBasePackageClasses = {com.simon.spring.basics.properties.SomeExternalService.class})


查看完整回答
反對 回復 2023-09-20
  • 1 回答
  • 0 關注
  • 96 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號