首页 > 解决方案 > Spring Boot @Autowired 字段为空

问题描述

我的Abc.classabcController中有一个为空的字段:

@Service(id = "ABC", name = "service-abc") // THIS IS NOT SPRING ANNOTATION it marks class as Service Singleton, loads custom annotations like @AfterInitialization
@SpringBootApplication
@ComponentScan(basePackages = "com.package*")
@ComponentScan("healthchecker")
public class Abc {
    
    @Autowired
    AbcController abcController;

    @AfterInitialization
    public void afterInit() throws GwConfigurationException {

        // initialize Spring Boot
        SpringApplication application = new SpringApplication(Dmsgw.class);

        // run with command line arguments
        CmdLineArguments cmdLineArguments = new CmdLineArguments();
        String[] args = cmdLineArguments.getArgStrings();
        
        if (args == null) {
            args = new String[0];
        }
        
        application.run(args);
 
        abcController.doSomething(); // abcController is null
    }
}

这是我的AbcController.class

@Service
public class AbcController {

    ...// some fields

    ...// some methods
}

到目前为止,我尝试abcController使用@Serviceor@Component或 or进行注释,@Controller但它是相同的。

这是MyServiceConfiguration.class

@Configuration
public class ServiceConfiguration {

    @Bean
    public AbcController defaultAbcController() {
        return new AbcController();
    }
}

我检查并加载了Bean。

标签: javaspring-boot

解决方案


推荐阅读