【发布时间】:2019-10-07 10:32:43
【问题描述】:
我在 springboot 项目上创建了一个 JPA 类:-
package com.example.demo.jpa;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.Users;
@Repository
public interface AppRepo extends CrudRepository<Users, Integer>, AppRepoCustom {
public List<Users> findAllByJob(String job);
}
另一个AppRepoCustom接口是这样的:
package com.example.demo.jpa;
import java.util.List;
public interface AppRepoCustom {
public List<String> getAllNames();
}
接口的实现:-
package com.example.demo.jpa;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.example.demo.model.Users;
public class AppRepoCustomImpl implements AppRepoCustom {
@PersistenceContext
EntityManager entityManager;
@Override
public List<String> getAllNames() {
Query query = entityManager.createNativeQuery("SELECT name FROM springbootdb.Users as em ", Users.class);
return query.getResultList();
}
}
现在在我的控制器类中,我正在注入 AppRepo 对象
@Autowired
AppRepo appRepo;
我的问题是我没有在任何地方指定要注入的 AppRepo 实现,那么 spring 如何能够在没有任何错误的情况下注入它? 当我们创建接口类型的对象时,如 Interface objectName = new implClass();其中 implClass 包含接口方法的所有实现。但在上面的示例中,一些实现在 CrudRepository 类中,一些在 AppRepoCustom 中,所以这个对象创建在这里如何工作?我很困惑。当我们创建像 Interface objectName = new implClass(); 和在给定场景中的对象时,内部对象是如何创建的。
【问题讨论】:
标签: java spring spring-boot jpa