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 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 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.

你可能感兴趣的:(问题记录)