简体   繁体   中英

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.

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. So I created a config class like this

@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

@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 .

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. Please verify that your AppConfig class is in the same (or under the same) package as your Main class.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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