字段需要一个类型为...的Bean,但找不到

时间:2019-02-27 08:54:06

标签: java spring spring-annotations

在我的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注释,但这无济于事。我还能做什么?

2 个答案:

答案 0 :(得分:2)

确保prod配置文件已启用,例如通过:

  1. JVM属性:

    -Dspring.profiles.active=prod

  2. 或环境变量:

    export spring_profiles_active=prod

  3. 或在创建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 {
    // ...
}
相关问题