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

   2024-10-01 5450
核心提示:在Spring Boot多模块项目中,通常会有一个主项目和多个子模块。为了在子模块中使用@Autowired注解注入依赖,需要做一些配置。在

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

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

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

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号