Spring環境はオブザーバーモードApplicationListenerを使用します

Spring環境はオブザーバーモードApplicationListenerを使用します

デモ

特定のイベントオブジェクトクラス

public class MyEvent extends ApplicationEvent {
    
    

    public MyEvent(Object source) {
    
    
        super(source);
    }

    public <T> T getEventSource(Class<T> tClass){
    
    
        return JSON.parseObject(String.valueOf(getSource()),tClass);
    }
}

抽象的なイベントオブザーバー

public abstract class AbMyApplicationListener implements ApplicationListener<MyEvent> {
    
    

    @Override
    public void onApplicationEvent(MyEvent event) {
    
    
        System.out.println("收到的监听事件抽象类:");
        //子类去实现具体逻辑
        execute(event);
    }

     abstract void execute(MyEvent event);
}

特定の実装ロジックサブクラス

@Component
public class MyApplicationListener extends AbMyApplicationListener {
    
    
    @Override
    void execute(MyEvent event) {
    
    
        System.out.println("我收到了通知,我是具体执行业务逻辑的子类:"+ event.getEventSource(Map.class));
    }
}

ApplicationContextを取得する

@Component
public class ApplicationContextUtil implements ApplicationContextAware {
    
    

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    
    
        this.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
    
    
        return applicationContext;
    }
}

観察された、イベント発行者

@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class AppTest {
    
    
    @Test
    public void test() {
    
    
        Map<String,String> map = new HashMap<>();
        map.put("name","zhangsan");
        map.put("age","22");
        MyEvent myEvent = new MyEvent(JSON.toJSONString(map));
        ApplicationContext applicationContext = ApplicationContextUtil.getApplicationContext();
        applicationContext.publishEvent(myEvent);
    }
}

jdkには実装オブザーバーが付属しています

おすすめ

転載: blog.csdn.net/qq_37904966/article/details/108475880