Juan Reina Pascual
Juan Reina Pascual

Reputation: 4588

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);
  }
}

Upvotes: 4

Views: 4022

Answers (1)

Sergii Bishyr
Sergii Bishyr

Reputation: 8641

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.

Upvotes: 7

Related Questions