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 'a.b.c.Dictionary' that could not be found. Consider defining a bean of type 'a.b.c.Dictionary' in your configuration.

What am I doing wrong?

Thanks


Solution 1:

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.