[英]Why does Spring Autowire fail when I move @SpringBootApplication?
[英]SpringBootApplication does not Autowire my Services
我的Spring Boot初始化時遇到了麻煩。 我在一個簡單的Spring Boot項目中有這個結構。
com.project.name
|----App.java (Annoted with @SpringBootApplication and Autowire MyCustomService)
|----com.project.name.service
|----MyCustomService.java (Annoted with @Service)
我嘗試在SpringBootApplication Annotation中設置scanBasePackages
屬性但不起作用。 無論如何,我有@Bean
注釋,我看到Spring Boot在應用程序中正確注入它,因為我可以在運行應用程序時看到日志,如下所示:
2019-03-09 15:23:47.917 INFO 21764 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'jobLauncherTaskExecutor'
...
2019-03-09 15:23:51.775 INFO 21764 --- [ Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'jobLauncherTaskExecutor'
我的AppClass.java的基本方案
@SpringBootApplication(
exclude = { DataSourceAutoConfiguration.class }
//,scanBasePackages = {"com.project.name.service"}
)
public class App{
private static Logger logger = LoggerFactory.getLogger(App.class);
@Autowired
private static MyCustomService myCustomService;
public static void main(String[] args) {
SpringApplication.run(App.class, args);
...
myCustomService.anyMethod();//NullPointerException
}
}
@Bean
public ThreadPoolTaskExecutor jobLauncherTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(25);
return executor;
}
我想我錯過了一些東西,但我正在閱讀一些指南而且沒有找到任何相關內容。
Spring不能@Autowire
靜態字段,使用ApplicationContext
來獲取bean
@SpringBootApplication(
exclude = { DataSourceAutoConfiguration.class }
//,scanBasePackages = {"com.project.name.service"}
)
public class App{
private static Logger logger = LoggerFactory.getLogger(App.class);
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(App.class, args);
MyCustomService myCustomService = (MyCustomService)context.getBean("myCustomService");
...
myCustomService.anyMethod();
}
}
或者您可以使用CommandLineRunner
@SpringBootApplication(
exclude = { DataSourceAutoConfiguration.class }
//,scanBasePackages = {"com.project.name.service"}
)
public class App implements CommandLineRunner {
private static Logger logger = LoggerFactory.getLogger(App.class);
@Autowired
private MyCustomService myCustomService;
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
public void run(String... args){
myCustomService.anyMethod();
}
}
問題已經解決,請看下面的鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.