SpringCloud多模块的时候,通常会把业务模块和公共模块分开
第一种方式:
示例:
<modules>
<module>eureka-server</module>
<module>gateway-server</module>
<module>config-server</module>
<module>course-server</module>
<module>schedule-server</module>
<module>enrollment-server</module>
<module>auth-server</module>
<module>core-server</module>
</modules>
core模块里面既有配置类,又有entity实体类和mapper层,
那么业务层,例如auth模块如何使用core模块里面的公共资源呢
@SpringBootApplication
@ComponentScan(basePackages = {"org.example.authserver", "org.example.core"})
@MapperScan("org.example.authserver.mapper")
public class AuthServerApplication {
public static void main(String[] args) {
SpringApplication.run(AuthServerApplication.class, args);
}
}
使用@ComponentScan扫描指定的core包及其子包下带有特定注解的类,将这些类注册为 Spring 容器中的 Bean
至于我的core里的mapper怎么扫描到呢?
@Configuration
@MapperScan("org.example.core.mapper") //指定Mapper接口所在的包
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new MybatisPlusAllSqlLog());
//分页插件配置
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return mybatisPlusInterceptor;
}
}
因为core里面有各种配置类,比如我这个mybatisplus的配置类,我们可以在这里面用@MapperScan扫描当前包的mapper,这样在auth模块就可以使用了
第二种方式:
我直接把所有的与数据库一一对应的实体和mapper单独放到一个mybatis模块,其他所有的配置类放在core模块,而且还可以做个自定义注解,自定义将core里面的哪些bean注入到spring容器
例如:
@Slf4j
@EnableCommonConfig
@EnableDiscoveryClient
@MapperScan("cn.ctwing.iot.ipark.mybatis")
@EnableFeignClients(basePackages = {"cn.ctwing.iot.ipark.openservice.feignclient", "cn.ctwing.iot.ipark.common.feign"}) //扫描Feign
@SpringBootApplication(scanBasePackages = {"cn.ctwing.iot.ipark"}) //扫描所有模块含该包路径下Spring容器要管理的Bean
public class IparkOpenServiceApplication {
public static void main(String[] args) {
SpringApplication.run(IparkOpenServiceApplication.class, args);
System.err.println("=============================================");
System.err.println("iot-ipark-openservice-application started successfully");
System.err.println("==============================================");
}
}
@EnableCommonConfig是自定义注解,
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Import({CommonConfig.class})
@Documented
public @interface EnableCommonConfig {
}
使用了 @Import({CommonConfig.class}),@Import
注解的作用是导入一个或多个配置类到 Spring 容器中
@Import({
SpringBeanUtil.class,
SpringContextHolder.class
})
@Configuration
public class CommonConfig {
}
这样的话,我可以指定只让SpringBeanUtil和SpringContextHolder注入到spring容器,
然后在我的业务模块就可以使用了