小编典典

SpringBootApplication不会自动连线我的服务

spring-boot

我的Spring Boot初始化遇到麻烦。我在一个简单的Spring Boot项目中具有此结构。

com.project.name
|----App.java (Annoted with @SpringBootApplication and Autowire MyCustomService)
|----com.project.name.service
     |----MyCustomService.java (Annoted with @Service)

我尝试scanBasePackages在SpringBootApplication
Annotation中设置属性,但不起作用。无论如何,我都带有@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;
}

我想我缺少了一些东西,但是我正在阅读一些指南,但对此一无所获。


阅读 327

收藏
2020-05-30

共1个答案

小编典典

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