简体   繁体   中英

Observer on Entity does not always work

I have a spring boot and spring data setup (@Data). I need to do some actions when a property of one entity is changed. I am trying to use the observer pattern, so when we call the setter of that property from the code I have added the stateChanged there. Do you think that will work as expected, or spring is calling the setters behind the scene?

Spring is definitely not calling these setters from time to time.

To execute your custom code right before an entity update is persisted in the database you could use the @PreUpdate annotation on a method in your entity class, or you could have a higher level abstract entity class with this method, if your @PreUpdate code is the same.

@PreUpdate
public void onPreUpdate() {
    //your custom code here
}

Doing this you can remove the stateChanged calls from your setters.

We had similar needs for two different scenarios and had to use two different solutions.

For hibernate entities we used org.hibernate.event.service.spi.EventListenerRegistry to the session factory and listened to required events like PRE_UPDATE or SAVE etc. Listener in our case is a spring bean and has requisite knowledge of other application. The event listener then notifies required bean about the event took place. But this is valid only hibernate events.

For other scenario, we had to inform other parts of the application something interesting happened. Not exactly observable pattern, but need was similar. We used org.springframework.context.ApplicationEventPublisher and other beans listened to desired types of events using org.springframework.context.ApplicationListener

In my experience second way was much cleaner as classes were not aware of each other. However if your entities are hibernate entities, this approach may not work.

I am still researching on that question. But.. I think I found the answer. Because I am sure I have seen setters getting called behind the scene in spring environment. ITS FROM THE AUTOWIRING- A PROPERTY AND AUTOWIRING IN THE CONSTRUCTOR

 @Autowired private ServiceTest testService;

vs

@Autowired
public ServiceOther(ServiceTest testService){
     this.testService = testService;
}

So Observer pattern can be applied to an Entity in the spring environment if we use Autowiring in the Constructor for that property.

Still not 1000% sure. So if anyone is good at the topic please explain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM