Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Springboot using @Autowired on constructor with parameter

I'm using springboot 1.3.8 and I have a @Autowired on a constructor with parameters but I get the error: No default constructor found...

@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);
  }
}
like image 320
Juan Reina Pascual Avatar asked Mar 08 '23 22:03

Juan Reina Pascual


1 Answers

Your class is annotated with @SpringBootApplication which is also @Configuration. And @Configuration should have a default no-args constructor. From javadoc:

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

Since Spring version 4.3 you can have constructor injection for @Configuration class. Tested on Spring Boot version 1.5.3 and it works fine.

Here are the release notes for Spring 4.3. And here is the feature that you need:

@Configuration classes support constructor injection.

like image 143
Sergii Bishyr Avatar answered Mar 12 '23 04:03

Sergii Bishyr