Irina
Irina

Reputation: 1265

@Autowired doesn't work for JpaRepository in standard App

When I am trying to run code based on this and this tutorials the error occurred:

Field userRepository in hello.MainController required a bean of type 'hello.UserRepository' that could not be found.

Application code:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Controller code:

    @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);
        }

    }

Repository code:

public interface UserRepository extends JpaRepository<User, Long> {
    User findAny();
}

There are no other error occurred. I can't understand the reason.

Before, in another project, simple code provided strange error: 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

Upvotes: 1

Views: 275

Answers (2)

Irina
Irina

Reputation: 1265

I was missing "boot" keyword in one of dependencies in pom.xml.

Upvotes: 0

mdeterman
mdeterman

Reputation: 4389

Use the @Repository annotation on your interface.

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    User findAny();
}

Another option is package scanning @EnableJpaRepositories

@EnableJpaRepositories(basePackageClasses=UserRepository.class)
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Upvotes: 2

Related Questions