解决springboot启动扫描不到⾃定义注解的问题对于⾃定义注解这⾥就不唠叨了,百度⼀⼤堆,这⾥有我⼀个⾃定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface MsgEvent {
RetailOrderEvent msgEvent();
}
注解实现类
@Component
public class MsgEventProcessor implements BeanPostProcessor {
/**
* 事件消息注解与实例Bean的映射对象
*/
public static Map<String, ServiceBean> EVENTCODESERVICEBEANMAP = new HashMap<String, ServiceBean>();
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Method[] methods = Class());
if (methods != null) {
for (Method method : methods) {
MsgEvent myMsgEvent = AnnotationUtils.findAnnotation(method, MsgEvent.class);
if (myMsgEvent != null) {
String eventCode = myMsgEvent.msgEvent().eventCode();
ServiceBean servieBean = new ServiceBean();
servieBean.setServiceBeanObj(bean);
servieBean.setServiceMethod(method);
Class<?> argsCls = ParameterTypes()[0];
servieBean.setArgsCls(argsCls);
EVENTCODESERVICEBEANMAP.put(eventCode, servieBean);
}
}
}
return bean;
}
}
调⽤者
@MsgEvent(msgEvent = RetailOrderEvent.PLACE_GENERALRETAILORDER)
public Person getPerson(Person p) {
Id());
}
spring boot debug模式下启动⼀直不会再代码红⾊部分停下,说明没有获取到⾃定义注解
原因是发现bean为jdk代理
解决办法
@SpringBootApplication
@EnableAspectJAutoProxy(exposeProxy = true)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
或者
@ImportResource(locations = { "l" })
@SpringBootApplication
//@EnableAspectJAutoProxy(exposeProxy = true)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="/schema/beans"
xmlns:xsi="/2001/XMLSchema-instance"
xmlns:context="/schema/context"
xmlns:aop="/schema/aop"
xsi:schemaLocation="/schema/beans
/schema/beans/spring-beans-3.1.xsd
/schema/context
/schema/context/spring-context-3.1.xsd
springboot aop
/schema/aop
/schema/aop/spring-aop-3.1.xsd ">
<!-- 配置使Spring采⽤CGLIB代理 -->
<aop:aspectj-autoproxy expose-proxy="true" proxy-target-class="true" />
</beans>
上述会让所有的都采⽤CGLIB代理,如果只想对使⽤的类采⽤,其他的还是原来的话就可以对注解使⽤类上标注
@Configuration代替@Component
补充知识:解决Aspect注解基于注解的增强不⽣效的问题
Aspect基于注解的增强⽣效须满⾜3个条件:
<!--1.代理⽅式设置为 cglib,默认false,则必须通过实现某个接⼝才能实现增强 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!--2.配置⽂件中把须增强注解所在包扫描注⼊,或者配置 bean-->
<context:component-scan base-package="注解所在包路径"/>
<!--3.配置⽂件中把@Aspect注解所在类对应包扫描注⼊或者配置bean-->
<context:component-scan base-package="aspect注解所在包路径"/>
ps : 若在 controller 层使⽤,则controller 也需要配置上边两个条件⽅能⽣效
以上这篇解决spring boot启动扫描不到⾃定义注解的问题就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。