我正在使用Spring MVC,我有许多Formatter<T>
类,类似这样的
@Component
public class DeporteFormatter implements Formatter<Deporte> {
...
@Autowired
public DeporteFormatter(SomeDependency someDependency){
this.someDependency = someDependency;
}
我有自定义的MvcInfrastructureConfiguration
课程
@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);
}
}
...
我对以下内容感到困惑:
如果我使用
//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;
}
formatters
实例变量永远不会被注入,我得到一个NullPointerException ..
但如果我使用
@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;
//}
一切正常..
为什么呢?我认为@Autowired应该无关紧要地工作(当然是不好的做法在实例变量中使用它在基础设施bean中因为测试问题而存在)