SpringBootApplication不会自动连线我的服务

时间:2019-03-09 14:33:39

标签: java spring 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)

我尝试在SpringBootApplication注释中设置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;
}

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

该问题之前已解决,请参见下面的链接

why can't we autowire static fields in spring