崛起于Springboot2.X + 事件监听器(71)

原创
01/03 18:00
阅读数 572

《SpringBoot2.X心法总纲》 

事件主题:认识一个女孩之后,触发事件监听,得到结果:认识到了一个女孩

1、配置

@Component
public class Girl {
    private String id;
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
@Component
public class UnderstandEvent extends ApplicationEvent {

    public UnderstandEvent(Girl source) {
        super(source);
    }

    public Girl know(){
        return (Girl) getSource();
    }
}

2、事件发布

@Service
public class GirlService {

    @Autowired
    ApplicationEventPublisher applicationEventPublisher;

    public void knowGirl(Girl girl){
        applicationEventPublisher.publishEvent(new UnderstandEvent(girl));
    }

    @EventListener
    public void afterKnow(UnderstandEvent understandEvent){
        Girl girl = understandEvent.know();
        System.out.println("认识了一个新女孩,她的名字叫" + girl.getName());
    }
}

3、contoller层

@Autowired
GirlService girlService;

@GetMapping(value = "/know")
public void know(){
    Girl girl = new Girl();
    girl.setId("12323");
    girl.setName("杨幂");

    girlService.knowGirl(girl);
}

4、测试结果

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部