上学期学完spring的基本增删改查后,还曾有点小小的得意,感觉自己也算知道不少的编程知识了,但这段时间的项目经验又一次次的教了自己做人,不断出现的新知识让自己目不暇接,知道的越多,未知的越多。也算进入了学习的另一个阶段:知道自己不知道感慨完了,该进入正题了,本周有一个需求,spring sercurity要求在保存密码的时候密码必须加密,学长开始写的时候是在setter密码的时候调用加密方法,不够优雅,就让我把这个方法提出来,换用监听器,当监听的user保存时就自动加密其密码,由于当时只知道拦截器,于是就去找了一篇拦截器的教程,发现写出来感觉相当不合适,就问学长,果然我理解错了意思,是用一个叫实体监听器(Entity Listeners)的东西。Entity Listener顾名思义,它可以监听实体的某些行为,并进行一部分操作。Hibernate支持的回调注解@PrePersistExecuted before the entity manager persist operation is actually executed or cascaded. This call is synchronous with the persist operation.在数据持久化到数据库之前执行@PreRemoveExecuted before the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.执行数据删除之前调用@PostPersistExecuted after the entity manager persist operation is actually executed or cascaded. This call is invoked after the database INSERT is executed.在执行数据插入之后调用@PostRemoveExecuted after the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.在执行数据删除之后调用@PreUpdateExecuted before the database UPDATE operation.在执行数据更新之前调用@PostUpdateExecuted after the database UPDATE operation.在执行数据更新之后调用@PostLoadExecuted after an entity has been loaded into the current persistence context or an entity has been refreshed.在数据从数据库加载并且赋值到当前对象后调用用法首先,先定义一个操作用的类,并在其中写下你要用的方法,比如下面的方法就代表在用户持久化和更新的时候执行(只需注解就好,不用继承其他类)。然后在实体上声明,就完工了,相当简单。对于上面的代码,初学者可能会对这一段有疑惑 PasswordEncoder passwordEncoder = ContextConfig.getContext().getBean(PasswordEncoder.class);我开始也不明白,还是学长给我讲解的,这是获取PasswordEncoder的对象,学长给我讲了讲才大概明白了hibernate和spring是两个系统,spring管理的对象,hibernate注入不进来。如果不明白可以看看下面这个图。spring的ioc这篇文章写得挺不错,有兴趣可以看看。总结实体监听器虽然只是一个很简单的功能,但却非常强大与实用,同时了解到hibernate和spring并不是一个东西,以前一直以为hibernate是spring的一个小功能,同时对spring总算有了一丁点清晰的认识,总体状态还算满意,感谢学长们的帮助。