【问题标题】:Spring: How to inject a bean from another projectSpring:如何从另一个项目注入 bean
【发布时间】:2016-10-14 22:30:57
【问题描述】:

我有两个包 com.a.b.c 和 com.x.y.z。在 com.a.b.c 中,我定义了一个这样的组件:

@Named
public class MyClass
{
    @Inject
    public MyClass()
    {
    }
}

在 com.x.y.z 中,我有一个类,我想像这样注入 MyClassA:

public class MyOtherClass
{
     @Inject
     private MyClass myClass;
}

我需要进行哪些配置更改才能将 MyClass 注入 MyOtherClass?现在我收到构建错误

org.springframework.beans.factory.NoSuchBeanDefinitionException: 没有为依赖找到 [com.a.b.c.MyClass] 类型的合格 bean:预计至少有 1 个 bean 有资格作为此依赖的自动装配候选者

提前致谢。

【问题讨论】:

  • 您应该在 Spring Configuration 类上方的 @ComponentScan 注释中指定必要的包

标签: java spring spring-mvc dependency-injection


【解决方案1】:

在component-scan中指定包名来初始化bean。

XML 配置

<context:component-scan base-package="com.a.b.c" />

Java 配置类

@Configuration
@ComponentScan({"com.a.b.c", "com.x.y.z"})
class AppConfig{
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    相关资源
    最近更新 更多