1
votes

I use Spring Boot MVC application. I have a @Configuration class that initializes a bean into ApplicationContext using @Bean. I have a @Controller class into which I am trying to autowire the bean using @Autowired annotation.

Result: @Autowired field is null.

DEBUG: I tried to debug to see the order of execution. I was expecting to see that class annotated with @Configuration will run first to initialize bean into application context. However, controller class got instantiated first. Then @Bean method of configuration class got called next. Due to this bean is instantiated after controller and that is why Controller is not getting bean autowired.

Question: How to have @Configuration @Bean method execute prior to the controller class instantiation?


code for configuration class:

@Configuration
public class RootConfiguration2 {

    @Autowired
    private IService<ActBinding> bindingService;

    @Bean
    public Map<String, String> getBingindNameToRoutingKeyMap() throws Exception {
        ListOperation<ActBinding> operation = ListOperation.from("key", "name", "exchangeId");
        operation.sort("key", SortOrder.Ascending);
        Iterable<ActBinding> result = bindingService.list(operation).getResult();
        Map<String, String> bindingNameToRoutingKey = new HashMap<>();
        result.forEach(x -> bindingNameToRoutingKey.put(x.getName(), x.getKey()));
        return Collections.unmodifiableMap(bindingNameToRoutingKey);
    }
}
1
could you share the configuration class code? - Lucas Ross
Turn on logging and check for warning messages. - OrangeDog
You'd have to show the code for IService<ActBinding> and where you inject getBingindNameToRoutingKeyMap. It could be a circular dependency, though you did not mentioned such error. It could a typo when injection getBingindNameToRoutingKeyMap paired with @Autowring(required=false)... need more code. - alexbt

1 Answers

3
votes

I found two workarounds. Both solutions worked: 1. Use @Resource instead of @Autowired to inject the bean into controller. 2. Use @PostConstruct on the method annotated with @Bean in Configuration class.

Note: You dont have to do both of the changes. Any one of them should work.