In the following code, a MvcRequestMatcher.Builder bean is registered with application context.
@Bean
MvcRequestMatcher.Builder mvc(HandlerMappingIntrospector introspector) {
return new MvcRequestMatcher.Builder(introspector);
}
the method takes a introspector parameter which itself is autowired bean. My question is since it's not a constructor nor a setter, and there is no @Autowired annotation, what kind of injection is it?
It is called method injection. you can use it in configuring beans in @Configuration class, it gives more flexibility and makes it clear which dependencies are needed for specific methods. also you can use it when a dependency is not always required and should only be injected under certain conditions like this:
@Bean
public MyBean myBean(@Autowired(required = false) OptionalDependency optionalDependency) {
if (optionalDependency != null) {
// Use the optional dependency
} else {
// Handle the absence of the optional dependency
}
return new MyBean(optionalDependency);
}