64288

Spring Boot not autowiring @Repository

Question:

I'm trying to configure a datasource with Spring Boot but I'm getting org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mycompany.myapp.repository.UserRepository com.mycompany.myapp.service.AuthenticationServiceImpl.userRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mycompany.myapp.repository.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)}

These is my project structure:

Main Class:

package com.mycompany.myapp; @ComponentScan(basePackageClasses = {com.mycompany.myapp.domain.user.User.class, com.mycompany.myapp.repository.UserRepository.class, com.mycompany.myapp.service.AuthenticationServiceImpl.class}) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

Domain Class:

package com.mycompany.myapp.domain.user @Entity public class User { @Id @GeneratedValue private long id; @Column(nullable = false) private String name; @Column(nullable = false) private String lastName; @Column(nullable = false) private String password; @Column(nullable = false) private String email; public User() {} public User(String email, String password){ this.email = email; this.password = password; } }

Repository:

package com.mycompany.myapp.repository; public interface UserRepository extends CrudRepository<User, Long> { List<User> findByLastName(String lastName); }

Controller

package com.mycompany.myapp.service; @RestController public class AuthenticationServiceImpl implements AuthenticationService { @Autowired private UserRepository userRepository; @RequestMapping("/add") public User add(){ User user = new User(); user.setName("Juan"); user.setLastName("Sarpe"); user.setEmail("email@gmail.com"); userRepository.save(user); return user; } }

application.properties

spring.datasource.url:jdbc:mysql://localhost:3306/mydb spring.datasource.username=user spring.datasource.password=pass spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.jpa.hibernate.ddl-auto=update

I guess my app is not detecting my @Repository annotation on UserRepository. As far as I know, Spring Boot will automatically set my class as @Repository because it is extending CrudRepository. What am I doing wrong? (Notice that my Application class is on top of packages hierarchy).

Answer1:

Have you tried <a href="http://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/config/EnableJpaRepositories.html" rel="nofollow">@EnableJpaRepositories</a> in your configuration ?

Answer2:

<strong>In main class of spring boot you have to use this below annotation :</strong>

@SpringBootApplication @ComponentScan(basePackages = "basepackage") @EntityScan(basePackages ="basepackage") @EnableAutoConfiguration @EnableJpaRepositories(basePackages = "basepackage")

<strong>In Repository layer use below annotation :</strong>

import org.springframework.stereotype.Repository;

import org.springframework.transaction.annotation.Transactional;

@Transactional @Repositor

<strong>If you have any service layer then use below annotation in the implementation class:</strong>

import org.springframework.stereotype.Service; @Service

Answer3:

The standard way to configure is to create a base marker repository interface and provide that in the component scan.

public interface RepositoryPackage { }

Keep the interface RepositoryPackage in the same package as UserRepository.

@ComponentScan(basePackageClasses= "RepositoryPackage.class") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

Recommend

  • Enable json serialization of Multimap in Spring Boot Project
  • Capybara server & browser error with no trace on server
  • How to make repository be loaded lazily when I start application?
  • Adjusting size of in app screenshot
  • How to display asterisk for input in Java? [duplicate]
  • Python List of Tuples (Find value with key + check if exist)
  • iOS App crash issue `[UIWindow warpPoint:]`
  • Checking for valid enum types from protobufs
  • Fortran function variable length string return
  • separate tokens in batch file
  • Javascript inside HTML import not affecting imported HTML
  • How to define a custom accuracy in Keras to ignore samples with a particular gold label?
  • Debugging php script timeout?
  • Arraylist of strings into one comma separated string
  • How to use Typescript with libraries like Ampersand.js that parse configs to build prototypes
  • Spotify cocoalibspotify offline status set to 1 but all tracks stuck at waiting
  • How do I use libcurl to printf a remote FTP directory listing?
  • Multiplying polynomials/simplifying like terms
  • Floating parent div grows to hypothetical width of floating child div
  • Calculate time from document
  • I am consuming a WCF service that requires headers from a .NET 2 website. How can I programmatically
  • How to turn off notice reporting in xampp?
  • Using redis as an LRU cache for postgres
  • Send array to next viewcontroller iOs xcode [duplicate]
  • How to encrypt Connectionstring written in web.config from codebehind?
  • Computing the discrete fourier transform of audio data with FFTW
  • Grails - How to implement a foreign key relationship not using an id column?
  • Codeigniniter insert data through models and controller
  • Sign a Pdf using custom digital signature in Java
  • Using Service Component Runtime
  • PHP Permalinks.. how to change?
  • What does the “id” field in an Android “Google Play Music” broadcast intent correspond to?
  • convert json to excel in java
  • Create/delete users from text file using Bash script