我想在我的Repository层创建一个事件通知程序,以便我可以添加监听器。我正在使用Spring,我想知道这是不是这样做的方式?或者有没有更好的方法在Spring中实现通知/监听器?
@Repository
public class JdbcRepository {
private List<InsertListener> insertListeners;
public void insert(final SomeObject object) {
// Ommited code for brewity
for (InsertListener listener : insertListeners) {
listener.notifiy(...);
}
}
}
Spring config xml
<bean id="jdbcRepository" class="mypackage.JdbcRepository">
<property>
<bean ref="myRepositoryListeners" />
</property>
</bean>
<bean id="myRepositoryListeners" class="java.util.List">
<constructor-arg>
<list>
<ref bean="..." />
<ref bean="..." />
</list>
</constructor-arg>
</bean>
答案 0 :(得分:1)
你可以这样做
public class JdbcRepository {
@Autowired
ApplicationContext context;
Collection<InsertListener> listeners;
@PostConstruct
public void init() {
listeners = context.getBeansOfType(InsertListener.class).values();
}
...
context.xml中
<context:annotation-config />
<bean id="l1" class="InsertListener" />
<bean id="l2" class="InsertListener" />
<bean id="repo" class="JdbcRepository" />
答案 1 :(得分:0)