springboot项目类中方法加了@Transactional后,通过SpringUtil只能获取到代理对象,无法获取真实实例

项目中需要通过类上的自定义注解获取所有有这些注解的对象

SpringUtil.getApplicationContext().getBeansWithAnnotation(MyAnnotation.class);

然而在这些对象的方法中如果加入了@Transactional这类注解,这些对象就会变为代理对象,在代理对象中无法获取到注解里面定义的值。

obj.getClass().getAnnotation(MyAnnotation.class);

此时返回为空。

解决方法:

通过下面spring自带的方法判断该类是否是代理类

AopUtils.isAopProxy(obj);

再通过

AnnotationUtils.findAnnotation(obj.getClass(), MyAnnotation.class);

获取真实实例注解里面真正的值。

通过反射也可以实现此效果。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
对于这个问题,我可以为您提供以下建议: 1. 在Spring Boot项目中使用@Transactional注解需要配置事务管理器。可以通过在配置文件中添以下内容来配置使用的事务管理器: spring.datasource.url=jdbc:mysql://localhost:3306/db_name spring.datasource.username=db_username spring.datasource.password=db_password #特别要注意这个属性: #spring.jpa.show-sql=true #transactionManager spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImprovedNamingStrategy spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.use_sql_comments=true 2. 如果您需要在不同的方法中开启和关闭事务,可以将@Transactional注解添到相关方法上。如果希望整个类的方法都使用相同的事务,则可以将@Transactional注解添到类级别。 3. 还需要确保在pom.xml文件中添了以下依赖项: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> 以上仅供参考,具体实现会根据您的具体需求和项目情况而有所不同。希望可以帮助到您,谢谢!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值