溫馨提示×

Autowired在Spring Boot多模塊項目中的使用

小樊
128
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女