gpt4 book ai didi

java - SpringBootApplication 不会 Autowiring 我的服务

转载 作者:行者123 更新时间:2023-11-29 04:11:06 26 4
gpt4 key购买 nike

我在 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 注释中设置 scanBasePackages 属性,但不起作用。无论如何,我有一个 @Bean 注释,我看到 Spring Boot 将它正确地注入(inject)到应用程序中,因为当我像这样运行应用程序时,我可以看到日志:

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

关于java - SpringBootApplication 不会 Autowiring 我的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55078382/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com