向实体对象注入服务

Inject service to entity object

我想在持久化或更新之前为实体列设置一个值。为此,我想注入一个服务。

@Entity
@Configurable(autowire=Autowire.BY_TYPE)
@Table(name="WARD")
public class Ward {

@Column(name = "HOSPITAL_ID")
private Long hospitalId;

@Transient
@Autowired
private HospitalService hospitalService;

public Long getHospitalId() {
    return hospitalId;
}

public void setHospitalId(Long hospitalId) {
    this.hospitalId = hospitalId;
}

@PreUpdate
@PrePersist
private void preUpdatePersist(){
    if(hospitalId == null && hospitalService != null)
        hospitalId = hospitalService.getSelectedHospital().getId();
}}

这是我在网上找到的方法。但这不会注入 new Ward() 创建。如何向实体注入服务。

这是spring版本4.3.10,hibernate 4.2.7

您不能在实体中注入服务,因为该实体不是 Spring 托管 bean。

您可以创建一个包含 ApplicationContext 的助手 class:

@Component
public class ApplicationContextProvider implements ApplicationContextAware {

    private static ApplicationContext context;

    public static <T> T bean(Class<T> beanType) {
        return context.getBean(beanType);
    }

    public static Object bean(String name) {
        return context.getBean(name);
    }

    @Override
    public void setApplicationContext(@SuppressWarnings("NullableProblems") ApplicationContext ac) {
        context = ac;
    }
}

现在您可以使用它来访问您在实体中的服务:

@PreUpdate
@PrePersist
private void preUpdatePersist(){
    if(hospitalId == null && hospitalService != null)
        ApplicationContextProvider.bean(HospitalService.class);
        hospitalId = hospitalService.getSelectedHospital().getId();
    }
}