Spring机制支持通过@EventListener注释发布应用程序事件并侦听Spring组件中的这些事件。但是,我找不到在文档中特定范围内发送事件的任何信息。我对Vaadin的具体需求是:
@UIScope中的bean使用,即不应影响其他用户UI是可能的吗?注意:这并不是Vaadin的特例。我还可以问一下,如何使用Spring请求范围来完成它。
发布于 2018-08-02 09:06:42
TL;DR :我认为它已经按照您的要求工作了,
长篇版本:
文档对此有点不清楚,但是尝试了一个简单的测试:
发布事件的控制器:
@Controller
public class FooController {
@Autowired
private ApplicationEventPublisher publisher;
@GetMapping("/fireEvent")
public void fireEvent() {
publisher.publishEvent(new FooEvent(this));
}
}和一个范围内的bean,它听着:
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
@Component
public class FooListener {
@EventListener(FooEvent.class)
public void listen() {
System.out.println("I'm listening. PS : I am "+this.toString());
}
}当运行两个并发请求时,只有作用域为相同的httprequest的侦听器才会得到事件。
我的解释(没有仔细看过它,所以用一点盐来理解它):
在我看来,ApplicationEventMulticaster的ListenerRetriever使用BeanFactory来获取以前注册为侦听器的bean (按它们的名称),而且很明显,工厂将返回当前作用域中的bean。
发布于 2018-08-01 12:48:54
请看看这是否是你要找的:
主要应用:
package com.fg7.evision.EventList;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = "com.fg7.evision.EventList")
public class EventApplication {
public static void main(String[] args) {
MyScopedEvent event = new MyScopedEvent("hello world");
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(EventApplication.class);
ctx.publishEvent(event);
}
}活动:
package com.fg7.evision.EventList;
public class MyScopedEvent {
private String message;
public MyScopedEvent( String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}事件侦听器的作用域仅限于Singleton作用域。
package com.fg7.evision.EventList;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component(value = "listener")
public class ScopedEventListener implements BeanNameAware {
@Autowired
ConfigurableApplicationContext context;
String beanName;
@Override
public void setBeanName(String name) {
this.beanName = name;
}
@EventListener(condition = "@listener.getScope() == 'singleton'")
public void handleEvent(MyScopedEvent myScopedEvent) {
System.out.println(myScopedEvent.getMessage());
}
public String getScope(){
return this.context.getBeanFactory().getBeanDefinition(this.beanName).getScope();
}
}https://stackoverflow.com/questions/51396152
复制相似问题