下面是我的示例 Dao 和服务层。
所有内容都在不同的包中。 我正在使用 spring-boot 1.4。 Autowiring 的 Dao 接口(interface)如何直接调用 DaoImpl 方法? 在java中,接口(interface)可以引用子对象,但iterface.childMethod()是不可能的。 我的想法是,由于我正在进行依赖注入(inject),不知何故我在服务层接收到了 daoImpl 的对象。 谁能解释一下正在发生的事情的整个概念?
ISocietyAccountMasterDao
public interface ISocietyAccountMasterDao extends IGenericRepository<SocietyAccountMaster> {
List<SocietyAccountMaster> getAllSocietyAccounts(String societyId, Long accountTypeId);
}
SocietyAccountMasterDaoImpl
public class SocietyAccountMasterDaoImpl extends AbstractDao<String, SocietyAccountMaster>
implements ISocietyAccountMasterDao {
private final Logger logger = LogManager.getLogger(LoggingAspect.MANUAL);
@Override
public List<SocietyAccountMaster> getAllSocietyAccounts(String societyId, Long accountTypeId) {
Criteria cr = getEntityCriteria();
try {
cr.add(Restrictions.eq("societyId", societyId));
if (!StringUtils.isEmpty(accountTypeId)) {
cr.add(Restrictions.eq("accountType.id", accountTypeId));
}
return cr.list();
} catch (Exception e) {
logger.error("Error While Society Accounts", e);
throw new BindException(BindStatus.FAILURE, BindStatus.FAILURE_MSG);
}
}
ISocietyAccountingService
public interface ISocietyAccountingService {
List<SocietyAccountMasterDto> getAllSocietyAccounts(String societyId);
}
SocietyAccountingServiceImpl
@Service("societyAccountingService")
@Transactional
public class SocietyAccountingServiceImpl implements ISocietyAccountingService {
@Override
public List<SocietyAccountMasterDto> getAllSocietyAccounts(String societyId) {
List<SocietyAccountMasterDto> responses = new ArrayList<SocietyAccountMasterDto>();
List<SocietyAccountMaster> dbSocietyAccountMasters = societyAccountMasterDao.getAllSocietyAccounts(societyId,
null);
for (SocietyAccountMaster dbSocietyAccountMaster : dbSocietyAccountMasters) {
SocietyAccountMasterDto response = new SocietyAccountMasterDto();
response.setNickName(dbSocietyAccountMaster.getNickName());
response.setBankName(dbSocietyAccountMaster.getBankName());
response.setBalance(dbSocietyAccountMaster.getBalance());
responses.add(response);
}
return responses;
}
}
最佳答案
@Component
- 指示 bean 是自动扫描组件。这意味着当它作为 Autowiring 注入(inject)时,spring 将搜索带有 beanName 的 bean。
@Repository
- 表示持久层中的 DAO 组件可用作自动扫描组件。
如果看到@Repository
注释的实现如下所示:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any
*/
String value() default "";
}
该注解类使用@Component
进行注解,这使其可用于 Autowiring 。这就是 DAO impl 可以通过 Autowiring 提供给服务的原因,因为 Spring 自动检测它。
关于java - @Repository 和 @Autowired 在 Spring Boot Dao 和 Service Layer 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48787203/