Search code examples
springspring-mvcdependency-injectionguicespring-java-config

Spring DI fails in 4.2.x but succeed in 4.3.x


I am trying to import Beans from Guice Injector in a spring based web app and then want those imported beans to be injected in subsequent creation of other beans. How I am doing it: I am trying to register guice Injector as bean. And then use getInstance to register other bean from guice based project as bean in my project. In my java config :

@Bean
public Injector getInjector() {
    return Guice.getInjector();
}
@Bean
@Inject
public ABC aBC(Injector injector) {
    return injector.getInstance(ABC.class);
}

Then one of my implementation is as

public class XYZ {
@Inject
XYZ (final ABC abc) {
}

When I use Spring 4.3.x this works but 4.2.x fails giving error No default constructor found. Is there any difference between 4.3.x and 4.2.x Also I want to use 4.2.x only due to certain reasons.


Solution

  • Constructor injection was changed with 4.3, see https://spring.io/blog/2016/03/04/core-container-refinements-in-spring-framework-4-3#implicit-constructor-injection-for-single-constructor-scenarios

    You could try Autowired instead of Inject

    public class XYZ {
       @Autowired
       XYZ (final ABC abc) {
    }