我正在使用hibernate和JpaRepository + PostgreSQL。我有以下代码,侦听对数据库所做的任何修改。
public class PermitEntityListener {
@PrePersist
public void prePersist(Permit target) {
perform(target, INSERTED);
}
@PreUpdate
public void preUpdate(Permit target) {
perform(target, UPDATED);
}
@PreRemove
public void preRemove(Permit target) {
perform(target, DELETED);
}
@Transactional(MANDATORY)
private void perform(Permit target, Action action) {
EntityManager entityManager = BeanUtil.getBean(EntityManager.class);
entityManager.persist(new PermitHistory(target, action));
//Send permitHistory to client via websocket to update changes
PermitUpdates updates = new PermitUpdates();
updates.sendUpdatedPermit(new PermitHistory(target, action));
}
}
在perform方法中,将所做的更改更新到新表中。在这一点上,我也希望通过Web套接字将此“ PermitHistory”发送回给用户。这样,当用户修改/查看表时,在客户端,他将能够收到提示,要求您对字段进行新更改,以便他可以选择刷新以显示更新。
我创建了一个新类“ PermitUpdates”
public class PermitUpdates {
@Autowired
private SimpMessagingTemplate template;
public void sendUpdatedPermit(PermitHistory permitHistory) {
if (permitHistory != null) {
this.template.convertAndSend("/changes", permitHistory);
}
}
}
我还添加了一个WebSocketConfig类
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/changes");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gs-guide-websocket").withSockJS();
}
}
发生此错误:
Caused by: java.lang.NullPointerException
at com.example.historical.websoc.PermitUpdates.sendUpdatedPermit(PermitUpdates.java:19)
我在做什么错?我如何让spring为我创建对象?
答案 0 :(得分:2)
PermitUpdates的第19行是:this.template.convertAndSend("/changes", permitHistory);
?如果是这样,则不会注入模板,因为PermitUpdates不是由Spring创建的(请参阅PermitEntityListener方法private void perform(Permit target, Action action)
PermitUpdates updates = new PermitUpdates()
)
您必须让spring手动创建对象或注入属性。