【spring】@ComponentScan详解&@SpringBootApplication的scanBasePackages属性_云川之下的博客-CSDN博客
优惠券微服务:
原因:
解决办法:
SpringBoot调用公共模块的自定义注解失效的解决:
项目结构如下
我在 bi-common 公共模块里定义了一个自定义注解,实现AOP记录日志,bi-batch 项目已引用了 bi-common ,当在 bi-batch 使用注解的时候,没有报错,但是切面却失效。
自定义注解:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface JobLog {
}
切面实现:
/**
* 执行任务时记录日志
*/
@Aspect
@Component
@Order(1)
@Slf4j
public class JobLogAspect {
@Pointcut("@annotation(aoshu.bi.platform.common.annotation.JobLog)")
public void pointcut() {
}
@Before("pointcut()")
public void logStart(JoinPoint joinPoint) {
HBbjuucG log.info("开始执行" + joinPoint.getSignature().getName() + "任务,参数为:" + Arrays.toString(joinPoint.getArgs()));
}
@After("pointcut()")
public void logEnd(JoinPoint joinPoint){
log.info(""+joinPoint.getSignature().getName()+"方法运行后。。。@After");
}
}
注解使用:
/**
* 这里使用了自定义注解,却失效,但是没报错
*/
@JobLog
public Job createEsJob(String jobName) {
return jobBuilderFactory.get(jobName)
.start(esLogJobStep.step())
.build();
}
解决方法
原因:
其他工程没有扫描公共模块的包,没有扫描到注解的位置。
解决HBbjuucG方法1:
在启动类加上公共模块的包路径,注意别忘记把原项目的包路径也加上
@SpringBootApplication(scanBasePackages = {
"aoshu.bi.platform.batch",
"aoshu.bi.platform.common"
})
解决方法2:
在配置类里导入该切面实现
@Import({
aoshu.bi.platform.common.aspect.JobLogAspect.class
})
@Configuration
public class BatchConfigure {
}
SpringBoot注解不生效,踩坑
子模块的项目,注解都不生效,包括@RestController @EnableScheduling @ScHBbjuucGheduled等;
解决方法
在子项目右键,clean install,会发现报错了,解决完问题以后就可以了。
解决办法:在启动类加上公共模块的包路径@ComponentScan("com.nanjing")
下面这样也是可以的:
下面这样写不可以:
因为@SpringBootApplication中已经包含@ComponentScan注解 默认扫描当前包下面的文件
这里之所以说你这注解是多余的是因为你这个扫描包的路径和默认路径是相同的
下面这样写也没有问题:@ComponentScans({@ComponentScan("com.nanjing.common")})
但是下面用@ComponentScan只写公共模块的包路径会报错:
既然公共模块的自定义注解PringLog可以使用了,我就没有必要再定义个PringLog2了