为什么@Autowired在构造函数中失败而在WebMvcConfigurerAdapter子类中的实例变量中失败

时间:2014-09-14 23:24:07

标签: spring spring-mvc spring-3 spring-4 spring-ioc

我正在使用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中因为测试问题而存在)

0 个答案:

没有答案