温馨提示×

Autowired在Spring Boot多模块项目中的使用

小樊
84
2024-08-23 12:46:29
栏目: 编程语言

在Spring Boot多模块项目中,通常会有一个主项目和多个子模块。为了在子模块中使用@Autowired注解注入依赖,需要做一些配置。

  1. 在主项目的启动类中使用@ComponentScan注解指定要扫描的包路径,包括主项目和所有子模块的包路径。例如:
@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);
    }
}
  1. 在子模块中使用@Autowired注解注入依赖,确保被注入的类被Spring容器管理。例如:
@Component
public class SomeService {
    public void doSomething() {
        // do something
    }
}
@Service
public class SomeOtherService {
    
    @Autowired
    private SomeService someService;
    
    public void doSomethingElse() {
        someService.doSomething();
    }
}
  1. 确保子模块的包路径在主项目的@ComponentScan注解中被扫描到,以便Spring能够识别和管理子模块中的Bean。

通过以上配置,就可以在Spring Boot多模块项目中正常使用@Autowired注解来注入依赖。需要注意的是,子模块中的Bean必须被Spring容器管理才能够被注入,否则会出现NullPointerException异常。

0