Application 启动类:

 

@SpringBootApplication
@EnableConfigurationProperties
@ComponentScan(basePackages = { "com.testing"})
public class Application {
@Bean
RestTemplate restTemplate() {
return new RestTemplate();}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
System.out.println("成功启动");
}


Dao层:

 

 

public interface UserRepository extends JpaRepository<User, String>{
User findByUsername(String username); //
}
Service 层:注入一个继承了JPA 的接口,理论上spring boot 会把JPA 注入repository,该接口是一定不需要实现类的.
上述方法实现了按Username查询User实体,可以看到我们这里没有任何类SQL语句就完成了个条件查询方法。
这就是Spring-data-jpa的一大特性:通过解析方法名创建查询
@Service
public class DataInit {

@Autowired
UserRepository userRepository;
}


但是会提示错误:提示@Autowired 不能正常注入:

 

可正常编译,没法运行,gradle bootrun 时提示错误:

caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.testing.data.UserRepository com.testing.service.DataInit.userRepository; nested exception is org.spring

framework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.testing.data.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate

for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=userRepository)}

 

Execution failed for task ':bootRun'.

> Process 'command 'C:\Program Files (x86)\Java\jdk1.8.0_101\bin\java.exe'' finished with non-zero exit value 1

总结:

出现该类错误时,可有一下几个问题需要去检查:

1. 检查各类是否加了注解,包括@service,@repository 等等;(注意@Autowired放在service实现上,而不是接口类上面。)

2. 包是否正确扫描到,这个很重要!!!(我的问题就是因为这个)

 

SpringBoot项目的Bean装配默认规则是根据Application类所在的包位置从上往下扫描!

“Application类”是指SpringBoot项目入口类。这个类的位置很关键:

如果Application类所在的包为:com.boot.app,则只会扫描com.boot.app包及其所有子包,如果service或dao所在包不在com.boot.app及其子包下,则不会被扫描!

即, 把Application类放到dao、service所在包的上级,com.boot.Application

知道这一点非常关键,不知道spring文档里有没有给出说明,如果不知道还真是无从解决.

Spring Boot @Autowired 没法自动注入的问题_sed