Search code examples
javaspring-boothibernatespring-data-jpa

Spring @Autowired is not working for repository


I am trying to connect Mysql using Spring boot, unable to get the object of repository class using spring @Autowired. I have added the code and server start up error message,

enter image description here

  1. Main class
package com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
public class TestingDemo {

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

}

  1. ProductController class
package com.test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.test.service.IProductService;

@RestController
@RequestMapping(value="/products")
public class ProductController {

    @Autowired
    IProductService productService;

    @RequestMapping(method = RequestMethod.GET, value = {"/"})
    private void getAllProducts() {
        System.out.println("ProductController - getAllProducts");
        productService.getAllProducts();

    }
}


  1. ProductService class
package com.test.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.test.entity.Products;
import com.test.repository.ProductRepository;

@Service
public class ProductService implements IProductService {

    @Autowired
    private ProductRepository productRepository;

    public void getAllProducts() {
        System.out.println("Service class - Getting usage information");
        Products slm = productRepository.getReferenceById(1);
        System.out.println(slm.getId() +" :: "+slm.getName());
    }
}
  1. IProductService class
package com.test.service;

public interface IProductService {

    void getAllProducts();
}


5.ProductRepository class

package com.test.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.test.entity.Products;

@Repository
public interface ProductRepository extends JpaRepository<Products, Integer> {
    
}

  1. Products class
package com.test.entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "products")
public class Products {

    @Id
    @GeneratedValue
    @Column(name = "ID")
    private Integer id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "DESCRIPTION")
    private String description;

    @Column(name = "PRICE")
    private String price;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

}

application.properties (DB, USERNAME, PASSWORD updated based on db)

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/<<DB>>
spring.datasource.username=<<USERNAME>>
spring.datasource.password=<<PASSWORD>>
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

build.gradle

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.2.0'
    id 'io.spring.dependency-management' version '1.1.4'
}

group = 'com.test'
version = '0.0.1-SNAPSHOT'

java {
    sourceCompatibility = '17'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter',
            'org.springframework.boot:spring-boot-starter-web',
            'org.springframework.data:spring-data-jpa',
            'jakarta.persistence:jakarta.persistence-api'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

After executing getting as below


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.2.0)

2023-12-03T00:32:51.072+05:30  INFO 28376 --- [           main] com.test.TestingDemo                     : Starting TestingDemo using Java 17.0.6 with PID 28376 (D:\Learning\GradleSpringBootWithStarterJPA\GradleSpringBootWithStarterJPA\bin\main started by test in D:\Learning\GradleSpringBootWithStarterJPA\GradleSpringBootWithStarterJPA)
2023-12-03T00:32:51.077+05:30  INFO 28376 --- [           main] com.test.TestingDemo                     : No active profile set, falling back to 1 default profile: "default"
2023-12-03T00:32:52.737+05:30  INFO 28376 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
2023-12-03T00:32:52.753+05:30  INFO 28376 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-12-03T00:32:52.753+05:30  INFO 28376 --- [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.16]
2023-12-03T00:32:52.862+05:30  INFO 28376 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-12-03T00:32:52.865+05:30  INFO 28376 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1720 ms
2023-12-03T00:32:52.960+05:30  WARN 28376 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productController': Unsatisfied dependency expressed through field 'productService': Error creating bean with name 'productService': Unsatisfied dependency expressed through field 'productRepository': No qualifying bean of type 'com.test.repository.ProductRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2023-12-03T00:32:52.968+05:30  INFO 28376 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2023-12-03T00:32:52.994+05:30  INFO 28376 --- [           main] .s.b.a.l.ConditionEvaluationReportLogger : 

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-12-03T00:32:53.043+05:30 ERROR 28376 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field productRepository in com.test.service.ProductService required a bean of type 'com.test.repository.ProductRepository' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.test.repository.ProductRepository' in your configuration.



I tried by adding

@ComponentScan(basePackages = "com.test") @EntityScan("com.test") @EnableJpaRepositories(basePackages = "com.test") in main class it is not working.

Can any one guide me to resolve this issue?

I tried by adding 'org.springframework.data:spring-boot-starter-data-jpa', in repository class JpaRepository cannot be resolved to a type.

Difference for spring-boot-starter-data-jpa vs org.springframework.data:spring-data-jpa

Thanks for all the input


Solution

  • After updating with 'org.springframework.boot:spring-boot-starter-data-jpa' under dependency able to access the import org.springframework.data.jpa.repository.JpaRepository; and doing gradle clean, it is working as expected

    build.gradle

    plugins {
        id 'java'
        id 'org.springframework.boot' version '3.2.0'
        id 'io.spring.dependency-management' version '1.1.4'
    }
    
    group = 'com.prakash'
    version = '0.0.1-SNAPSHOT'
    
    java {
        sourceCompatibility = '17'
    }
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation 'org.springframework.boot:spring-boot-starter',
                'org.springframework.boot:spring-boot-starter-web',
                'org.springframework.boot:spring-boot-starter-data-jpa',
                'mysql:mysql-connector-java:8.0.31',
                'jakarta.persistence:jakarta.persistence-api'
        testImplementation 'org.springframework.boot:spring-boot-starter-test'
    }
    
    tasks.named('test') {
        useJUnitPlatform()
    }