Service not found a repository bean in my Springboot project

huangapple go评论76阅读模式
英文:

Service not found a repository bean in my Springboot project

问题

I see that you have provided a detailed description of your issue related to a Spring Boot project. It seems like you're facing a problem with the bean configuration. To resolve this, you should:

  1. Ensure that your UserRepository and UserService are in the correct packages.
  2. Make sure that the package containing your ServerApplication class is at or above the package containing your UserRepository and UserService so that Spring can scan and find these components.
  3. Check if your ServerApplication class is in the correct package or update the @ComponentScan annotation accordingly.
  4. Verify that your application's main class (the one annotated with @SpringBootApplication) is in the root package or configure the @SpringBootApplication annotation's scanBasePackages attribute to include your components' packages.

If you've already tried these steps and are still encountering issues, please provide more specific error messages or logs so that I can assist you further.

英文:

First of all, I want to give many thanks to everyone who read my question and want to help me solve it so, I have a problem which about not found bean in my project. I have a repository named "UserRepository" and in my service is "UserService" has @Autowired that repository, its not found my repository although I added repository annotation. "UserService" not found the repository bean

This is my problem:
> ***************************
> APPLICATION FAILED TO START
> ***************************
>
> Description:
>
> Parameter 0 of constructor in com.baothien.server.User.UserService required a bean of type 'com.baothien.server.User.UserRepository' that could not be found.
>
>
> Action:
>
> Consider defining a bean of type 'com.baothien.server.User.UserRepository' in your configuration.
>
>
> Process finished with exit code 0

My Project Structure:
My project structure

UserRepository.java

package com.baothien.server.User;

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

import java.util.List;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    @Query("SELECT * FROM Users")
    List<User> getAllUsers();
}

UserService.java

package com.baothien.server.User;

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

import java.util.List;

@Service
public class UserService {
    @Autowired
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public List<User> getAllUsers() {
        return userRepository.getAllUsers();
    }
}

UserController.java

package com.baothien.server.User;

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

import java.util.List;

@RestController
@RequestMapping("/api/v1")
public class UserController {
    @Autowired
    private final UserService userService;
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/test")
    public String test() {
        return "GET User API succesfully!";
    }

    @GetMapping("/get-users")
    public List<User> getUsers() {
        return userService.getAllUsers();
    }
}

User.java

package com.baothien.server.User;

import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;

@Entity
@Table
@Data
@NoArgsConstructor
public class User {
    @Id
    @SequenceGenerator(
            name = "user_sequence",
            sequenceName = "user_sequence",
            allocationSize = 1
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "user_sequence"
    )
    private Long id;
    private String email;
    private String fullName;
    private String role;
    private String password;
}

Main method

package com.baothien.server;

import com.baothien.server.User.UserController;
import com.baothien.server.User.UserRepository;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EntityScan(basePackages = {"com.baothien.server.User.*"})
@EnableJpaRepositories(basePackages = {"com.baothien.server.User.*"})
public class ServerApplication {

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

}

I tried my best but this problem was not solved, I really need a solution.
Thanks for reading my question, see you.

UPDATE: I use @ComponentScan:

@ComponentScan(basePackages = "com.baothien.server.User.*")

It run but when I test on Postman, it has White Label Error, not found page (http://localhost:8080/api/v1/test). As you see, my controller has /test path, I don't understand why it have this error.

I tried find the solution on many forum but cannot solve that problem

答案1

得分: 1

  1. 你不需要@EntityScan
  2. 你不需要@EnableJpaRepositories
  3. 在Spring Data存储库接口上的@Repository不起作用。
  4. JpaRepository或者更确切地说是CrudRepository已经有一个findAll方法来检索所有实体。放弃你的getAllUsers方法。
  5. 你正在使用错误的@Id,你正在使用Spring Data的@Id,而你需要使用jakarta.persistence@Id

第4和第5点实际上是你的问题,因为你写的查询是错误的,应该是SELECT u FROM User u。这是JPQL查询,而不是SQL查询。但是正如我所说,你不需要它,因为已经有一个findAll方法。对于JPA实体来说,需要一个@Id,所以这也会导致失败。

英文:

You are trying to hard.

  1. You don't need @EntityScan
  2. You don't need @EnableJpaRepositories
  3. @Repository on a Spring Data repository interface doesn't do anything
  4. JpaRepository or rather CrudRepository already has a findAll to retrieve all entities. Ditch your getAllUsers method.
  5. You are using the wrong @Id you are using the Spring Data one whereas you need the jakarta.persistence one.

Point 4 and 5 are actually your issues as the query you have written is wrong it should read SELECT u FROM User u. It is a JPQL and not a SQL query. However as stated you don't need it as there is already a findAll method. An @Id for JPA entities is required, so that makes it fail as well.

答案2

得分: 0

Your basePackages is too narrow. Try

EntityScan(basePackages = {"com.baothien.server"})

英文:

Your basePackages is too narrow. Try

EntityScan(basePackages = {"com.baothien.server"})

huangapple
  • 本文由 发表于 2023年4月17日 02:25:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76029600.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定