springboot无法注入JpaRepository的问题

使用内置服务器启动springboot项目时,会从@SpringBootApplication修饰类所在的包开始,加载当前包和所有子包下的类,将由@Component @Repository @Service @Controller修饰的类交由spring进行管理。

package com.facade;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class Application {
	public static void main(String[] args) {
		ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
		String[] profiles = context.getEnvironment().getActiveProfiles();
		if (profiles != null) {
			for (String profile : profiles) {
				System.out.println("------------start with profile : " + profile);
			}
		}
	}
}

在使用Spring data jpa时,通常都是继承Repository接口相关的其他接口,然后Spring data jpa在项目启动时,会为所有继承了Repository的接口(@NoRepositoryBean修饰除外)创建实现类,并交由Spring管理。例如,

package com.facade.repository;

import org.springframework.data.repository.PagingAndSortingRepository;
import com.facade.entity.HttpDoc;

public interface HttpDocRepository extends PagingAndSortingRepository<HttpDoc, Long> {

}

package com.facade.service;

import com.facade.entity.HttpDoc;

public interface HttpDocService {

	public HttpDoc save(HttpDoc entity);
	
	public HttpDoc getById(Long id);
	
	public Iterable<HttpDoc> findAll();
	
}

package com.facade.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.facade.entity.HttpDoc;
import com.facade.repository.HttpDocRepository;
import com.facade.service.HttpDocService;

@Service
@Transactional
public class HttpDocServiceImpl implements HttpDocService {

	@Autowired
	private HttpDocRepository httpDocRepository;

	@Override
	public HttpDoc save(HttpDoc entity) {
		return httpDocRepository.save(entity);
	}

	@Override
	public HttpDoc getById(Long id) {
		return httpDocRepository.findOne(id);
	}

	@Override
	public Iterable<HttpDoc> findAll() {
		return httpDocRepository.findAll();
	}

}

以上代码Application处于HttpDocRepository HttpDocServiceImpl的根目录中,所以HttpDocRepository是可以被成功注入到HttpDocServiceImpl中的。
如果将Application移动到其他平行目录或者子目录,就算使用scanBasePackages指定扫描目录也无法将HttpDocRepository成功注入,会产生如下错误描述

Action:

Consider defining a bean of type 'com.facade.repository.HttpDocRepository' in your configuration.

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值