事件监听器模式示例
// 自定义事件监听器
public interface MyEventListener extends EventListener {
void update(MyEvent event);
}
// 监听对象
public class MyEvent extends EventObject{
public MyEvent(Object o){
super(o);
}
}
// 自定义事件监听器实现类
public class MyEventListenerImpl implements MyEventListener {
@Autowired
private UserDao userDao;
@Override
public void update(MyEvent event) {
User user = (User)event.getSource();
userDao.update(user);
}
}
// 需要监听的业务逻辑
public class TestServiceImpl() implements ApplicationContextAware{
private static Map<String, ChargeEventListener> observer;
private static ApplicationContext applicationContext;
// 从Bean中获取监听器
@PostConstruct
public void init(){
observer = applicationContext.getBeansOfType(MyEventListener.class);
}
// 获取Spring上下文
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
applicationContext = ctx;
}
// 业务逻辑
public void test(){
User user = new User();
user.setName("test");
/*触发监听模块*/
for(MyEventListener value : observer.values()){
value.update(new MyEvent(charge));
}
}
}