简体   繁体   中英

Destroy all session scoped bean of a class

Is there any way to destroy all created session scoped bean of a particular class (and let spring recreate when needed) ?

For example, 2 users visit the application, and then there will be 1 bean for each of the user. I would like to destroy all these 2 beans.

Use case:

a admin is updating the menu bar. menu bar list data are stored in a session scoped bean. the admin's bean should be destroyed and the menu bar should be updated. and of course the others' menu should be updated as well, so the others bean should be destroyed as well.

note 1: different user may see different menu, so the bean is session scoped, not singleton.

note 2: i do not want to invalidate whole session of the user, but just only that bean

i found this way to destroy the current scope bean. but i am not able to destroy bean from other session.

((ScopedObject) myBean).removeFromScope();

Thanks a lot !!

Destroying beans and recreating them seems overkill and a little messy too.
For such approaches I would favor events and Spring provides a Spring Event API ( spring-context dependency).
You could inject an ApplicationEventPublisher instance in the bean class that provokes the state change for some other beans and these beans could register a even listener ( @EventListener(condition = "...")) to read this change event.

For example the publisher :

@Component
public class PublisherBean{

    private final ApplicationEventPublisher publisher;

    @Autowired
    public PublisherBean(ApplicationEventPublisher publisher) { ... }

    public void createOrder(Order order) {
        // ....
        this.publisher.publishEvent(new OrderCreatedEvent(order)); 
    }    
}

Subscribers/Listeners :

@Component
public class ListenerBean{

  @EventListener(condition = "#creationEvent.awesome")
  public void handleOrderCreatedEvent(CreationEvent<Order> creationEvent) {
    ... 
  }

}

You could see more information here .

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