El entorno de Spring usa el modo de observador ApplicationListener

El entorno de Spring usa el modo de observador ApplicationListener

manifestación

Clase de objeto de evento específico

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);
    }
}

Observador de eventos abstractos

public abstract class AbMyApplicationListener implements ApplicationListener<MyEvent> {
    
    

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

     abstract void execute(MyEvent event);
}

Subclase de lógica de implementación específica

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

Obtener 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;
    }
}

Observado, editor de eventos

@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 viene con observador de implementación

Supongo que te gusta

Origin blog.csdn.net/qq_37904966/article/details/108475880
Recomendado
Clasificación