在Spring Boot多模塊項目中,通常會有一個主項目和多個子模塊。為了在子模塊中使用@Autowired注解注入依賴,需要做一些配置。
@SpringBootApplication
@ComponentScan(basePackages = {"com.example.main", "com.example.submodule1", "com.example.submodule2"})
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
@Component
public class SomeService {
public void doSomething() {
// do something
}
}
@Service
public class SomeOtherService {
@Autowired
private SomeService someService;
public void doSomethingElse() {
someService.doSomething();
}
}
通過以上配置,就可以在Spring Boot多模塊項目中正常使用@Autowired注解來注入依賴。需要注意的是,子模塊中的Bean必須被Spring容器管理才能夠被注入,否則會出現NullPointerException異常。