bula
bula

Reputation: 9439

Inject service to entity object

I want to set entity column a value before persist or update. For that, I want to inject a service.

@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();
}}

This is the way I found in internet. But this does not inject on new Ward() creation. How can I inject a service to entity.

This is spring version 4.3.10, hibernate 4.2.7

Upvotes: 1

Views: 1723

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36223

You can't inject a service in an entity because the entity is not a Spring managed bean.

You can create a helper class that holds the ApplicationContext:

@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;
    }
}

Now you can use that to access your service in the entity:

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

Upvotes: 3

Related Questions