Spring : 在服务中注入数据对象

Spring : injecting data object in service

由于JPA和Spring有不同的上下文管理,不建议创建一个数据对象class同时带有注解@Component和@Entity。

但是如果没有@Component,数据对象就无法通过@Autowired 注入到服务中。

但是用 new 创建我的数据对象的新实例对我来说似乎是一种回归。

是否有在 spring 托管服务中注入数据对象 (@Entity) 的好方法?

数据对象:

@Component
@Entity
@Table(name = "user")
public class UserDo {
//data object stuff ...

服务:

@Service("listAllGoods")
@Transactional(propagation = Propagation.REQUIRED)
public class ListAllGoods implements IListGoodService{

@Autowired
private IGoodDao goodDao;

@Autowired
private UserDo user;

//option 1 : works but not recommended because forces @Component on data object
@Override
public List<GoodDo> createGood() {
    user.setName("Roger");
    return goodDao.create(user);
}

//option 2 : 
// without @Autowired UserDo
// regression feeling
@Override
public List<GoodDO> createGood() {
    UserDo user = new UserDo();
    user.setName("Roger");
    return goodDao.create(user);
}

Spring 的主要特点是依赖注入。

Dependency or coupling, a state in which one object uses a function of another object

很明显 User 实体在您的情况下不是依赖项,因此使用 new 运算符创建它是最正确的方法。


另外,您说您希望每次引用您的服务时都创建 "dependency"。这是您在面试中可能遇到的 "How to update prototype bean in a singleton" 问题。这不在你的问题范围内,但我强烈建议你 google 这个。