gpt4 book ai didi

java - 在与当前类同名的类上使用 Spring @Autowired

转载 作者:行者123 更新时间:2023-11-29 07:32:43 26 4
gpt4 key购买 nike

假设我在 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:

Explicitly specify the name of the Spring bean definition associated with this Configuration class. If left unspecified (the common case), a bean name will be automatically generated. The custom name applies only if the Configuration class is picked up via component scanning or supplied directly to a AnnotationConfigApplicationContext.

编辑:

并使用相同的名称,同时使用 @Qualifier 注释在您的应用程序中 Autowiring 此 bean,如下所示:

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

关于java - 在与当前类同名的类上使用 Spring @Autowired,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39828220/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com