4

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);
  }
}
4
  • Answer is in your message. No default constructor i.e. public App() {...} available. Why don't you use @Autowired on fields? Commented Jun 2, 2017 at 12:17
  • Is CLIhelper is a bean? Commented Jun 2, 2017 at 12:22
  • Yes, CLIhelper is a bean, it´s anotated as @Component Commented Jun 2, 2017 at 12:28
  • Irother, I´d like to have a constructor with parameter to test some functionality. Some like this: Autowired private ApplicationContext context; Autowired private CLIHelper cliHelper; App app= new App(context, cliHelper); app.someMethods() Commented Jun 2, 2017 at 12:33

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.