java – 使用@Autowired在带有参数的构造函数上的Springboot

前端之家收集整理的这篇文章主要介绍了java – 使用@Autowired在带有参数的构造函数上的Springboot前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用 springboot 1.3.8并且我在带有参数的构造函数上有一个@Autowired但我得到错误:找不到默认构造函数

@SpringBootApplication
public class App implements CommandLineRunner {

  private ApplicationContext context;
  private CLIHelper cliHelper;

  @Autowired
  public App(ApplicationContext context,CLIHelper cliHelper) {
    this.context = context;
    this.cliHelper = cliHelper;
  }

  public static void main(String[] args) {
     SpringApplication.run(App.class,args);
  }
}

解决方法

您的类使用@SpringBootApplication注释,它也是@Configuration. @Configuration应该有一个默认的no-args构造函数.
javadoc开始:

@Configuration classes must have a default/no-arg constructor and may
not use @Autowired constructor parameters.

从Spring版本4.3开始,您可以为@Configuration类进行构造函数注入.在Spring Boot 1.5.3版本上测试,它工作正常.

Here是Spring 4.3的发行说明.以下是您需要的功能

@Configuration classes support constructor injection.

猜你在找的Springboot相关文章