2 回答
TA贡献2019条经验 获得超9个赞
请看看这是否是您要找的:
主要应用:
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;
}
}
事件侦听器的范围仅限于单例范围。
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();
}
}
- 2 回答
- 0 关注
- 190 浏览
添加回答
举报