user655145
user655145

Reputation:

Spring 3.1: How do I inject a bean created in a different configuration class

I'm just setting up a web application using Spring 3.1 and I'm trying to do this by using java configuration. I have two configuration classes "AppConfig" (general bean definitions) and "WebConfig" (Spring MVC configuration). How can I reference a bean that has been declared in AppConfig in the WebConfig class?

Below, the validator in the AppConfig configuration class should use the messageSource fromn WebConfig.

AppConfig:

@Configuration
@ComponentScan(basePackages = { "com.example" })
public class AppConfig {

    @Bean
    public Validator validator() {
        final LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setValidationMessageSource(messageSource());
        return validator;
    }

}

WebConfig:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.example.common.web", "com.example.web"  })
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ReloadableResourceBundleMessageSource messageSource() {
        final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages");
        return messageSource;
    }

}

When I want to reference a bean from the same configuration class, I'd just call its setup method, but I obviously cannot do this when the bean is declared in another class.

Your advice will be greatly appreciated!

Upvotes: 3

Views: 9878

Answers (3)

Amir Pashazadeh
Amir Pashazadeh

Reputation: 7322

There are two ways to do so:

public class WebConfig {
    @Autowired
    AppConfig appconfig;

    ...
}

or, as Aaron Digulla mentioned:

public class WebConfig {
    @Autowired
    Validator validator;

    ...
}

I prefer the first form, with one autowiring you can access the whole configuration, and then you can access its beans, by calling theNewBean.setValidator(appConfig.validator());.

Upvotes: 4

grepit
grepit

Reputation: 22392

I think Aaron Digulla and Amir Pashazadeh are both correct but there is also another annotation since JSR 330 was introduced. You can also use @Inject

@Inject
private Validator validator;

http://docs.spring.io/spring/docs/3.0.x/reference/beans.html#beans-autowired-annotation

Upvotes: 2

Aaron Digulla
Aaron Digulla

Reputation: 328790

Configurations are beans, too, so you can use @Autowired

public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private Validator validator;

    ...
}

Upvotes: 6

Related Questions