当我尝试根据 this 和 this 教程运行代码时,发生错误:< / p>
Field userRepository in hello.MainController required a bean of type 'hello.UserRepository' that could not be found.
申请代码:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
控制器代码:
@RestController
public class MainController {
@Autowired
private UserRepository userRepository;
@RequestMapping("/greeting")
public HttpEntity<Greeting> greeting(
@RequestParam(value = "name", required = false, defaultValue = "World") String name) {
Greeting greeting = new Greeting("...");
greeting.add(linkTo(methodOn(MainController.class).greeting(name)).withSelfRel());
return new ResponseEntity<Greeting>(greeting, HttpStatus.OK);
}
}
存储库代码:
public interface UserRepository extends JpaRepository<User, Long> {
User findAny();
}
没有发生其他错误。我无法理解原因。
之前,在另一个项目中,简单的代码提供了奇怪的错误:
call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@32eff876: startup date [Sun Oct 01 23:41:33 MSK 2017]; root of context hierarchy
答案 0 :(得分:1)
在界面上使用@Repository
注释。
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findAny();
}
另一个选择是包扫描@EnableJpaRepositories
@EnableJpaRepositories(basePackageClasses=UserRepository.class)
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
答案 1 :(得分:0)
我失踪了&#34; boot&#34; pom.xml中的一个依赖项中的关键字。