如何在以@Entity注释的类中使用@Autowired? [英] How to use @Autowired in an class annotated with @Entity?

查看:359
本文介绍了如何在以@Entity注释的类中使用@Autowired?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 TimeBooking 的实体.当我请求该实体并返回到客户端时,我想从存储库中获取ActivityTimeBookings的列表.但是当调用该函数时,存储库为空. 因此,我尝试@Autowired存储库,并将其标记为瞬态,并且还说Spring应当注入一个依赖项.

I have an entity called TimeBooking. When I request this entity and return to the client I want to get a list of ActivityTimeBookings from a repository. But when the function get called the repo is null. So I tried to @Autowired the repo and marked it as transient and also said Spring that there is a dependency which should be injected.

@Configurable(preConstruction = true)
@Entity
public class TimeBooking extends BaseEntity{

    @Autowired
    private transient ActivityTimeBookingRepository activityTimeBookingRepository;

    ...

    @JsonProperty("activityTimeBookings")
    private List<ActivityTimeBooking> activityTimeBookings() {
        return this.activityTimeBookingRepository.findByDate(this.timeFrom);
    }
}

有什么建议吗?

推荐答案

在带有@Entity注释的类中使用@Autowired是不好的做法.

Using @Autowired in a class annotated with @Entity is a bad practice.

解决方案如下:

1.创建服务界面:

public interface TimeBookingService {

   public List<ActivityTimeBooking> activityTimeBookings();

}  


2.创建服务接口的实现:

@Service
public class TimeBookingServiceImpl implements TimeBookingService {

    @Autowired
    private ActivityTimeBookingRepository activityTimeBookingRepository;

    public List<ActivityTimeBooking> activityTimeBookings() {
        return this.activityTimeBookingRepository.findByDate(this.timeFrom);
    }
}

这篇关于如何在以@Entity注释的类中使用@Autowired?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆