簡體   English   中英

Spring 啟動“無法自動裝配”

[英]Spring Boot "Could not Autowire"

Tomcat 總是崩潰並出現錯誤“無法自動連接...”我沒有正在使用 ArrayList 模擬的數據庫 btw

我的用戶界面:

public interface Users{

    Optional<User> findbyId(int id);

    void create(User user);

    void changesomething(User user);
}

class 用戶,ID 為 email,nutzername 和密碼:

@Data
public class User{

    int id;

    String email;

    String nutzername;

    String password;
    
}

我的服務 Class 帶有服務注釋:

@Service
public class UserService implements Users{

    private final ArrayList<User> userlist;

    public UserService(ArrayList<User> userlist) {
        this.userlist = userlist;
    }

    @Override
    public Optional<User> findbyId(int id) {
        if(userlist.get(id) != null){
            return Optional.of(userlist.get(id));
        }else {
            return Optional.empty();
        }

    }

    @Override
    public void create(User user) {
        userlist.add(user);
    }

    @Override
    public void changesomething(User user) {
        int id = user.getId();
        findbyId(id).get().setPassword(user.getPassword());
        findbyId(id).get().setEmail(user.getEmail());
        findbyId(id).get().setPassword(user.getPassword());
    }
}

和 Rest Controller 來處理收到的 JSON:

@RestController
@RequestMapping("/api/users")
public class UserController {

    private Logger logger = LogManager.getLogger();
    private final Users users;

    public UserController(Users users) {
        this.users = users;
    }

    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity create(@RequestBody UserRepresentation userRepresentation){
        try {
            users.create(userRepresentation.toUser());
            logger.info("User with id" + userRepresentation.getId() + " created!");
            return ResponseEntity.ok().build();
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResponseEntity.internalServerError().build();
        }
    }

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<UserRepresentation> findbyID(@RequestParam("id")int id){
        try {
            if(users.findbyId(id).isPresent()){
                logger.info("User with Id: " + id + " is Present");
                return ResponseEntity.ok(UserRepresentation.from(users.findbyId(id).get()));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e){
            logger.error(e.getMessage());
            return ResponseEntity.internalServerError().build();
        }
    }

    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity updateUser(@RequestBody UserRepresentation userRepresentation){
        try {
            if(users.findbyId(userRepresentation.getId()).isPresent()){
                logger.info("User with Id: " + userRepresentation.getId() + " is Present");
                users.changesomething(userRepresentation.toUser());
                logger.info("User with Id: " + userRepresentation.getId() + " updated");
                return ResponseEntity.ok().build();
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e){
            logger.error(e.getMessage());
            return ResponseEntity.internalServerError().build();
        }
    }
}

這里顯示的錯誤:

2022-07-30 11:38:36.455  INFO 22648 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1888 ms
2022-07-30 11:38:36.531  WARN 22648 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancellin
g refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController' defined in URL [jar:file:/C:/Use
rs/chris/Desktop/SWT-Programmieren/Users/rest-api/target/rest-api-1.0-SNAPSHOT.jar!/de/christoph/UserController.class]: Unsatisfied dependency expressed through con
structor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'de.christoph.Users' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2022-07-30 11:38:36.538  INFO 22648 --- [           main] o.a.c.c.StandardService                  : Stopping service [Tomcat]
2022-07-30 11:38:36.569  INFO 22648 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-07-30 11:38:36.611 ERROR 22648 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Parameter 0 of constructor in de.christoph.UserController required a bean of type 'de.christoph.Users' that could not be found.


Action:

Consider defining a bean of type 'de.christoph.Users' in your configuration.

如果您需要更多信息,請給我發短信謝謝您的幫助:)

您需要在UserController中將@Autowired添加到您的用戶 class 。

public class UserController {

    private Logger logger = LogManager.getLogger();

@Autowired
    private final Users users;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM