我不太明白为什么这段代码会让我找不到默认构造函数'错误。构造函数是@Autowired。一切似乎都正确注入。有人可以帮忙吗?感谢
@SpringBootApplication
public class Application {
private ApplicationContext applicationContext;
private MessagingService messagingService;
private Parser parser;
private static final Logger log = LoggerFactory.getLogger(Application.class);
@Autowired
public Application(ApplicationContext applicationContext,
MessagingService messagingService,
Parser parser)
{
this.applicationContext = applicationContext;
Assert.notNull(messagingService, "MessagingService must not be null");
this.messagingService = messagingService;
Assert.notNull(parser, "Parser must not be null");
this.parser = parser;
}
public static void main (String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner app() {
return args -> {
Locale defaultLocale = Locale.getDefault();
Locale.setDefault(defaultLocale);
log.info("Using MessagingService: " + messagingService.getMyMessageCode());
parser.parse();
};
}
}
修改:更新 Application.class
@SpringBootApplication
public class Application {
@Autowired
private MessagingService messagingService;
@Autowired
private Parser parser;
private static final Logger log = LoggerFactory.getLogger(Application.class);
public Application() {}
public static void main (String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner app() {
return args -> {
Locale defaultLocale = Locale.getDefault();
Locale.setDefault(defaultLocale);
log.info("Using MessagingService: " + messagingService.getMyMessageCode());
parser.parse();
};
}
}
答案 0 :(得分:4)
来自luboskrnac的回答是正确的。
但如果你真的想使用 Constructor Injection
,你可以升级 SpringBoot
版本到 1.4.0.RELEASE
,将使用 Spring 4.3.2.RELEASE
@Configuration
类
答案 1 :(得分:3)
您无法自动加入主Spring Boot类。您可以注入CommandLineRunner
所需的依赖项作为使用@Bean
注释的方法的参数,当然还要删除主类的构造函数注入:
@SpringBootApplication
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main (String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner app(ApplicationContext applicationContext,
MessagingService messagingService,
Parser parser) {
return args -> {
Locale defaultLocale = Locale.getDefault();
Locale.setDefault(defaultLocale);
log.info("Using MessagingService: " + messagingService.getMyMessageCode());
parser.parse();
};
}
}
编辑: 编辑后更正上下文配置:
@SpringBootApplication
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public Application() {}
public static void main (String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner app(MessagingService messagingService, Parser parser) {
return args -> {
Locale defaultLocale = Locale.getDefault();
Locale.setDefault(defaultLocale);
log.info("Using MessagingService: " + messagingService.getMyMessageCode());
parser.parse();
};
}
}