cdoe
cdoe

Reputation: 469

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

Upvotes: 1

Views: 502

Answers (2)

Udit kaushik
Udit kaushik

Reputation: 51

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 {
}

Upvotes: 0

S.Tushinov
S.Tushinov

Reputation: 648

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.

Upvotes: 3

Related Questions