簡體   English   中英

在與當前類同名的類上使用Spring @Autowired

[英]Spring @Autowired on a class with the same name as the current class

假設我在Spring Boot應用程序中具有以下類:

@Configuration
public class Environment {
    @Autowired
    org.springframework.core.env.Environment environment;
}

運行時,我得到:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field environment in com.example.Environment required a bean of type 'org.springframework.core.env.Environment' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.core.env.Environment' in your configuration.

Disconnected from the target VM, address: '127.0.0.1:57780', transport: 'socket'

解決此問題的方法是將我的班級從public class Environment重命名為public class Environments

但是我不想那樣做。 如何保留我的班級名稱,又如何使Spring意識到我要做什么?

您應該為您的配置命名:

@Configuration(value = "myEnviroment")
public class Environment {}

來自@Configuration文檔,關於value

明確指定與此Configuration類關聯的Spring bean定義的名稱。 如果未指定(通常情況),將自動生成Bean名稱 僅當通過組件掃描拾取Configuration類或將其直接提供給AnnotationConfigApplicationContext時,自定義名稱才適用。

編輯:

並在使用@Qualifier注釋在應用程序中自動裝配此bean時使用相同的名稱,如下所示:

@Autowired @Qualifier("myEnvironment")
private Environment environment;

您可以為您的類指定一個bean名稱,並自動將其連接到新bean,最后將它們自動裝配到類

      @Autowire("newname")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM