Search code examples
javaspringspring-java-config

Java Config same annotation bean in multiple config classes


I am trying to switch to java config from xml.

We have a core library, and then implementations that use the core library. We also have webapp and cli in each implementation. I am trying to modularize the config. We do use component scanning for certain packages. I am running into a circular dependency issue in the config classes. I need to inject the same @Component into beans created in multiple java config classes. My configs are as follows:

@Configuration
@ComponentScan(basePackages = {"my.components"})
@ImportResource({
        "classpath:data-access-config.xml"
})
@PropertySource(value = "classpath:core.props", ignoreResourceNotFound = true)
public class CoreAppConfig {
    @Autowired
    Environment env;

    @Autowired
    ComponentBean bean;

    @Bean
    public MyBean myBean() {
        return new MyBean(bean);
    }
}


@Configuration
@Import({CoreAppConfig.class})
@PropertySource(value = "classpath:my-app.props")
public class MyAppConfig {
    @Autowired
    Environment env;

    @Autowired
    ComponentBean bean;

    @Bean
    public MyBean2 myBean2() {
        return new MyBean2(bean);
    }
}


@Configuration
@ComponentScan(basePackages = {"my.app.services"})
@Import({MyAppConfig.class, CoreAppConfig.class})
public class MyWebAppConfig {
    @Autowired
    Environment env;

    @Autowired
    MyAppConfig myAppConfig;

    @Autowired
    ComponentBean bean;

    @Bean
    public MyRestService myRestService() {
        return new MyRestService(bean);
    }
}

What would be the best way to solve this?

1 option would be to not use component scanning. Others?

EDIT:

The exception I am getting is BeanCurrentlyInCreationException. If I remove the @Import({CoreAppConfig.class}) or the @Autowired ComponentBean Bean from MyAppConfig, the problem goes away.

EDIT 2:

So I think this is a circular dependency problem with the specific bean. I can do what I want with other beans, Only this specific bean is giving me problems.

Any tips on determining the circular dependency?

EDIT 3:

okay so I've figured out the culprit. In CoreAppConfig I create a Bean MyPropsBean. Then in MyAppConfig, I create the same MyPropsBean. I was hoping to override the CoreAppConfig.MyPropsBean with MyAppConfig.MyPropsBean. I think this is causing the issue since both CoreAppConfig and MyAppConfig autowire the ComponentBean. How can I resolve this? Whats the best way to override a bean?


Solution

  • so i solved this by moving the creation of the MyAppConfig bean to a separate config class. Then I use @PropertySources and create the MyAppConfig bean passing in the dynamic param.