Lah*_*age 2 java spring spring-boot
我的Controller类如下.
@Controller
public class app {
@GetMapping(path = "/")
public @ResponseBody
String hello() {
return "Hello app";
}
}
Run Code Online (Sandbox Code Playgroud)
当我浏览网址时,它工作正常.但是,当添加以下代码时,它说"Could not autowire. No beans of 'NoteRepository' type found".
@Autowired
NoteRepository noteRepository;
// Create a new Note
@PostMapping("/notes")
public Note createNote(@Valid @RequestBody Note note) {
return noteRepository.save(note);
}
Run Code Online (Sandbox Code Playgroud)
App控制器类与主类(运行应用程序)所在的包相同.但是当我们将上面的代码添加到不同包中的控制器时,它不会显示错误.但是当我们通过url导航甚至是一个简单的get方法时它不起作用.
我的主要课程如下.
@SpringBootApplication
@EnableJpaAuditing
public class CrudApplication {
public static void main(String[] args) {
SpringApplication.run(CrudApplication.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
我的Repository类是
@Repository
public interface NoteRepository extends JpaRepository<Note, Long> {
}
Run Code Online (Sandbox Code Playgroud)
我的项目结构
我想找到解决方案:
注入一个实例NoteRepository.我总是收到消息"无法自动装配.没有找到类型的bean"错误.Spring不能注入它,如果接口在相同或不同的包中则无关紧要.
我无法在控制器(MyController)中运行位于与应用程序入口点不同的包中的方法.
主要症状是:
App控制器类与主类(运行应用程序)所在的包相同.但是当我们将上面的代码添加到不同包中的控制器时,它不会显示错误.但是当我们通过url导航甚至是一个简单的get方法时它不起作用.
默认情况下,Spring Boot应用程序只会自动发现在与主类相同的包中声明的bean.对于位于不同包中的Bean,您需要指定包含它们.你可以用@ComponentScan它.
package foo.bar.main;
//import statements....
//this annotation will tell Spring to search for bean definitions
//in "foo.bar" package and subpackages.
@ComponentScan(basePackages = {"foo.bar"})
@SpringBootApplication
@EnableJpaAuditing
public class CrudApplication {
public static void main(String[] args) {
SpringApplication.run(CrudApplication.class, args);
}
}
package foo.bar.controller;
//import statements....
//since @ComponentScan, now this bean will be discovered
@Controller
public class app {
@GetMapping(path = "/")
public @ResponseBody
String hello() {
return "Hello app";
}
}
Run Code Online (Sandbox Code Playgroud)
要使Spring Data能够识别应创建哪些存储库,您应该@EnableJpaRepositories向主类添加注释.此外,为了使Spring Data和JPA实现扫描实体,请添加@EntityScan:
@ComponentScan(basePackages = {"foo.bar"})
@SpringBootApplication
@EnableJpaAuditing
@EnableJpaRepositories("your.repository.packagename")
@EntityScan("your.domain.packagename")
public class CrudApplication {
//code...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5670 次 |
| 最近记录: |