I am working through Spring MVC and I have many Formatter<T>
classes, something like this
@Component
public class DeporteFormatter implements Formatter<Deporte> {
...
@Autowired
public DeporteFormatter(SomeDependency someDependency){
this.someDependency = someDependency;
}
I have my customized MvcInfrastructureConfiguration
class
@EnableWebMvc
@Configuration
@ComponentScan(basePackages={"..."})
public class MvcInfrastructureConfiguration extends WebMvcConfigurerAdapter {
private Set<Formatter<?>> formatters;
...
@Override
public void addFormatters(FormatterRegistry registry) {
if(formatters==null)
logger.error("dependency is null");
logger.info("formatters.size(): {}", formatters.size());
for(Formatter<?> formatter : formatters){
registry.addFormatter(formatter);
}
}
...
I am confused with the following:
If I use
//Mandatorily asked for by Spring
public MvcInfrastructureConfiguration(){
logger.info("MvcInfrastructureConfiguration Constructor...");
}
@Autowired
public MvcInfrastructureConfiguration(Set<Formatter<?>> formatters){
logger.info("MvcInfrastructureConfiguration Constructor with parameter");
this.formatters = formatters;
}
the formatters
instance variable never is injected and I get a NullPointerException..
But if I use
@Autowired
private Set<Formatter<?>> formatters;
//Mandatorily asked for by Spring
public MvcInfrastructureConfiguration(){
logger.info("MvcInfrastructureConfiguration Constructor...");
}
//public MvcInfrastructureConfiguration(Set<Formatter<?>> formatters){
//logger.info("MvcInfrastructureConfiguration Constructor with parameter");
//this.formatters = formatters;
//}
All works fine..
Why? I thought @Autowired should work without matter his location (of course is bad practice use it in instance variables in not infrastructure beans due the problems with Testing)