在我的Spring
项目中,我有一个界面:
public interface MyIntefrace {
void myMethod(String myParam);
}
我有一个实现它的类:
@Component
@Profile("prod")
public class MyImplementationClass implements MyInterface {
...
在另一堂课中,我按如下方式使用此对象:
@Autowired
MyInterface myinterface;
...
myinterface.myMethod(someParam);
它给我抛出一个错误:
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
我尝试在@Service
上方添加MyInterface
注释,但这无济于事。我还能做什么?
答案 0 :(得分:2)
确保prod
配置文件已启用,例如通过:
JVM属性:
-Dspring.profiles.active=prod
或环境变量:
export spring_profiles_active=prod
或在创建ApplicationContext
时以编程方式:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
//...........
ctx.getEnvironment().setActiveProfiles("prod");
ctx.refresh();
答案 1 :(得分:0)
@KenChan提供的答案已经提到了可行的解决方案,但是我想补充一些其他细节。当前,您只有MyIntefrace
的一种实现,该实现也用@Profile
进行了注释。如果不使用此概要文件运行应用程序,则无法创建所有其他依赖于该bean的bean(并且没有选择使用getter / setter注入进行注入)。
我建议您创建第二个实现(如果未激活您的概要文件则将注入该实现),或者对该概要文件也注释所有依赖的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 {
// ...
}