所以我有我的 Subject 类:
@Component
public class Subject<T extends Monitorable> {
@Autowired
private List<Observer<T>> observers;
public void fireListeners(T monitorable){
for (Observer<T> observer : observers) {
observer.doSome(monitorable);
}
}
}
这是一种为 Monitorable 的每个实现创建新主题实例的方法,例如:
@Autowired
private Subject<Trip> tripSubject;
Trip 是一个 Monitorable,它有自己的观察者
@Autowired
private Subject<Truck> truckSubject;
还有卡车
问题是。它只创建一个 Subject,所有观察者混合在一起,如何在不为每个可监视对象创建新的 Subject 类的情况下将它们分开?
最佳答案
这不是您问题的答案,但可能是您问题的解决方案:Spring 4.2 具有内置事件(观察者)机制:
@Autowire ApplicationEventPublisher publisher;
public void doSomething() {
...
//fire the event
publisher.publishEvent(new YourEvent());
...
}
一些其他的bean:
//This is the observer, it "catch" the event
@EventListener
public void handleOrderCreatedEvent(YourEvent your) {
...
}
关于java - 如何为每个泛型类型创建一个新的 bean 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47950148/