@Autowired Failing to inject Repostiory into Controller in Springboot application

52 Views Asked by At
  • Here I have a simple Springboot app using JpaRepository and I am failing to inject Repository into controller.
  • Domain: Amenity, Controller: AmenityController, Repository: AmenityRepository
package com.example.demo.repository;

import com.example.demo.domain.Amenity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.stereotype.Repository;

@Repository
public interface AmenityRepository extends JpaRepository<Amenity, Long> {
}
package com.example.demo.domain;

import lombok.*;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Table(name = "amenity_table")
@Setter
public class Amenity {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
}
package com.example.demo.domain;

import lombok.*;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Table(name = "amenity_table")
@Setter
public class Amenity {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
}

The error I'm getting is:

Error creating bean with name 'amenityController': Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'amenityRepositoryChild'

I've tried changing from field injection to constructor injection and it is still not working. I have also tried a lot of different methods but nothing seems to work.

1

There are 1 best solutions below

0
Min Yul On

Umm.. The entity in the question appears to be duplicated. There is also no code for the Controller provided.

The root-level Bean, annotated with @SpringBootApplication, requires configuration to scan for repositories. For example, we need to include code like this

@SpringBootApplication
@EnableJpaRepositories(basePackages = {"com.company.store.infrastructure.jpa.repository"})
public class StoreJpaApplication {

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

Could you add this to the implementation?