【发布时间】:2019-06-24 14:25:33
【问题描述】:
我在使用 Spring AOP 时在数据库中保存日志(或任何其他信息)时遇到问题。
这是问题的根源:
@Aspect
@Configuration
@Component
@EnableAspectJAutoProxy
public class LoggingAspect {
@Autowired
private LogService logService;
@AfterThrowing(pointcut = "execution(* org.springframework.web.client.RestTemplate+.*(..))", throwing = "ex")
public void logError(Exception ex) {
Log log = new Log("Error!");
logService.save(log);
}
}
logService 实例是一个简单的@Service 类,它在内部调用@Repository 方法。没什么特别的。 Log 类更简单:)它只包含一个变量(如果我们包含 id,则为两个):
@Entity
@Table
public class Log {
@Id
private Long id;
@Column
private String message;
//getters, setters, constructors, etc.
}
LoggingAspect 工作正常。 @AfterThrowing 建议在任何异常的情况下被正确调用。但是在调用save 方法后,数据库中没有保存任何内容。
当我尝试调用 getAll() 方法而不是 save 时,一切都按预期工作。所有数据都从数据库中加载。
此问题仅适用于save 方法。
如有任何提示,我将不胜感激。
编辑:
正如我之前提到的,@Service 和 @Repository 类目前非常基础。也许值得补充的是,外部方面类一切都运行良好。可以将日志保存在数据库中。此问题仅在保存时出现,并且仅在用于各种建议时才会出现。
添加服务代码
@Service
public class LogService {
@Autowired
private LogRepository logRepository;
@Transactional(readOnly = true)
public List<Log> getAllLogs() {
return logRepository.findAll();
}
@Transactional
public void save(Log log) {
logRepository.save(log);
}
}
添加了代码库
@Repository
public interface LogRepository extends JpaRepository<Product, Log> {
}
【问题讨论】:
-
请张贴
LogService代码 -
@ThomasAndolf
LogService代码添加 -
你有
@EnableJpaRepositories吗? -
不,但我使用 Spring Boot,所以我认为它是通过自动配置自动启用的。正如我在“编辑”中提到的那样 - 在方面类之外一切正常
-
供参考
By default, CRUD methods on repository instances are transactional. For read operations, the transaction configuration readOnly flag is set to true. All others are configured with a plain @Transactional so that default transaction configuration applies.docs.spring.io/spring-data/jpa/docs/2.1.8.RELEASE/reference/…
标签: spring spring-boot aop spring-aop