Home > Back-end >  Can't inject repository in springboot
Can't inject repository in springboot

Time:06-23

This is my repository:

@Repository
public interface GroupRepository extends JpaRepository<Group, Integer> {}

This is how I tried to use it in my service class:

@Service
public class GroupService {
    private final GroupRepository groupRepository;

    @Autowired
    public GroupService(GroupRepository groupRepository) {
        this.groupRepository = groupRepository;
    }

Got this error :org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'groupController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'groupService' defined in file [/Users/nathanxuan/Files/Project/ratingApp/target/classes/com/xjy/service/GroupService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'groupRepository' defined in com.xjy.mapper.GroupRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.xjy.pojo.Group

Does anyone know why this is happening? When I commented out the repository class everything works fine (I have another mapper class and that one also works).

-------edit----------- This is the structure of my app:

enter image description here

CodePudding user response:

I think the problem is with the model class Group, it needs the Entity annotation since you are using JPA. Try out this:

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Group {
    ....
}

Note: @Data @AllArgsConstructor @NoArgsConstructor comes from Lombok, so if you're not using it, just create regular Getter and Setter

CodePudding user response:

Try removing @Repository from your repository. By extending from JpaRepository should be enough.

Unless you really need a setter injection defining your repository in the service like this should also be fine and more concise.

@Autowired
private GroupRepository groupRepository;
  • Related