Spring 3 Java configuration: imported @ Configuration not expanded?

I have an application in which I am trying to use the latest Spring 3 conventions with annotation-based configurations, but I also have deprecated classes that use constructor injection. Based on the Spring documentation, you should simply call the method that creates this dependency and pass it to the constructor that needs it. This seems to work when the configuration class is extended, but it seems that if you are @Import for the Configuration class, it will not be extended, so it could potentially inject unauthorized instances.

In particular, if one of my repositories is injected by the constructor into another bean, and this repository is defined in the same configuration class as the other bean (I know that repositories must be in their own configuration class), then it is not associated with the injected EntityManager.

My Beans:

public class MyBean {
    private ShouldBeSingleton d;
    public @Autowired MyBean(ShouldBeSingleton d) { this.d = d; }   
    public ShouldBeSingleton getMyDependency() { return d; }
}

public class ShouldBeSingleton { 
}

And two configuration classes like this:

@Configuration
public class MyImportedConfig { 
    @Bean public ShouldBeSingleton mySingleton() {
        return new ShouldBeSingleton();
    }       
    @Bean public MyBean myBean() {
        return new MyBean(mySingleton());
    }       
}

@Configuration
@Import({MyImportedConfig.class})
public class MyConfig {
}

My main thing is this:

public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
    MyBean bean = context.getBean(MyBean.class);
    System.out.println("myInjectedSingleton=" + bean.getMyDependency());
    System.out.println("mySingleton=" + context.getBean(ShouldBeSingleton.class));
}

If I load MyImportedConfig.class, I get the correct output (i.e. the singleton class is the same if I call the method from MyImportedConfig):

myInjectedSingleton=test.ShouldBeSingleton@b42cbf
mySingleton=test.ShouldBeSingleton@b42cbf

But if I changed AnnotationConfigApplicationContext to load MyConfig, which imports MyImportedConfig, this happens:

myInjectedSingleton=test.ShouldBeSingleton@a9ae05
mySingleton=test.ShouldBeSingleton@1dff3a2

? , , EntityManager , , @Autowired Configuration, .

AnnotationConfigWebApplicationContext, ConfigLocation, , , , @Import.

+3
1

... , ?

+1

Source: https://habr.com/ru/post/1728713/


All Articles