简体   繁体   English

将非弹簧 object 注入 spring 项目

[英]Injecting a non-spring object into a spring project

Relatively new to Spring framework, so not sure if what I'm trying to do is even possible. Spring 框架相对较新,所以不确定我想要做的事情是否可行。

I have the following non-spring classes / interface.我有以下非弹簧类/接口。

package a.b.c;
    public interface Dictionary {
}

package a.b.c;
    public class EnglishDictionary implements Dictionary {
}

package a.b.c;
    public class FrenchDictionary implements Dictionary {
}

I want to inject these classes into a spring managed application.我想将这些类注入到 spring 托管应用程序中。 So I created a config class like this所以我像这样创建了一个配置 class

@Configuration
@ComponentScan({"a.b.c")}
public class AppConfig {

    @Bean
    Dictionary englishDictionary() {
        return new EnglishDictionary();
    }

    @Bean
    Dictionary frenchDictionary() {
        return new FrenchDictionary();
    }
}

And use these dictionaries in a Spring component class like this并像这样在 Spring 组件 class 中使用这些字典

@Component
public class MyClass {

    @Autowired
    Dictionary englishDictionary;
}

However, the application refuses to start with an error message saying " Field englishDictionary required a bean of type 'abc.Dictionary' that could not be found. Consider defining a bean of type 'abc.Dictionary' in your configuration .但是,应用程序拒绝以一条错误消息开始,该消息说“字段 englishDictionary 需要一个无法找到的 'abc.Dictionary' 类型的 bean。考虑在您的配置中定义一个 'abc.Dictionary' 类型的 bean

What am I doing wrong?我究竟做错了什么?

Thanks谢谢

Your AppConfig class is not getting picked up by the Spring context and this is why you're receiving this exception.您的AppConfig class 没有被 Spring 上下文拾取,这就是您收到此异常的原因。 Please verify that your AppConfig class is in the same (or under the same) package as your Main class.请确认您的AppConfig class 与您的Main class 位于相同(或在相同)package 中。

In other words, if your Main class is in package com.example.demo but your AppConfig class is in com.example.beans your Spring application will fail to start. In other words, if your Main class is in package com.example.demo but your AppConfig class is in com.example.beans your Spring application will fail to start.

From my perspective the better solution would be to have @Component(from Spring) annotation written at the class level.从我的角度来看,更好的解决方案是在 class 级别编写 @Component(from Spring) 注释。

package a.b.c;
    @Component
    public class EnglishDictionary implements Dictionary {
}

package a.b.c;
    @Component
    public class FrenchDictionary implements Dictionary {
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM