[英]Field required a bean of type … that could not be found
In my Spring
project I have an interface: 在我的
Spring
项目中,我有一个接口:
public interface MyIntefrace {
void myMethod(String myParam);
}
and I have a class that implements it: 我有一个实现它的类:
@Component
@Profile("prod")
public class MyImplementationClass implements MyInterface {
...
In my other class, I'm using this object as follows: 在另一堂课中,我按如下方式使用此对象:
@Autowired
MyInterface myinterface;
...
myinterface.myMethod(someParam);
And it throws me an error: 它给我抛出一个错误:
Field myinterface in mypackage required a bean of type ... that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Consider defining a bean of type '...' in your configuration
I tried to add @Service
annotation above MyInterface
but that didn't help. 我试图在
MyInterface
上方添加@Service
注释,但这没有帮助。 What else can I do? 我还可以做些什么?
Make sure the prod
profile is enable such as through : 确保通过以下方式启用
prod
配置文件:
JVM property : JVM属性:
-Dspring.profiles.active=prod
Or environment variable: 或环境变量:
export spring_profiles_active=prod
Or programmatically when creating ApplicationContext
: 或在创建
ApplicationContext
时以编程方式:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); //........... ctx.getEnvironment().setActiveProfiles("prod"); ctx.refresh();
The answer provided by @KenChan already mentioned a viable solution, but i wanted to add some additional details. @KenChan提供的答案已经提到了可行的解决方案,但是我想添加一些其他细节。 Currently, you only have one implementation of
MyIntefrace
, which is also annotated with @Profile
. 当前,您只有
MyIntefrace
一种实现,该实现还带有@Profile
注释。 If you don not run you application using this profile, all other beans that depend on that bean (and are not optionally injected using getter/setter injection) can not be created. 如果不使用此概要文件运行应用程序,则无法创建所有其他依赖于该bean的bean(并且没有选择使用getter / setter注入进行注入)。
I recommend you either create a second implementation that will be injected if your profile is not activated, or annotate all depending beans as well with that profile. 我建议您创建第二个实现(如果未激活您的概要文件时将注入该实现),或者对该概要文件也注释所有依赖的bean。
@Component
@Profile("prod")
public class MyImplementationClass implements MyInterface {
// ...
}
@Component
@Profile("!prod") // second implementation, used if 'prod' is not active
public class MyImplementationClass implements MyInterface {
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.