我的 class 中构造函数的参数 0 需要第二个 class 的 bean,但找不到

Parameter 0 of constructor in my class required a bean of my second class that could not be found

我知道这是一个已发布 100 次的问题,但不幸的是,我的 Spring Boot 应用程序出现 Defining Bean 错误,我真的不知道为什么。我没有看到我从启动到完成的错误,因为我正在定义一个 bean。

如有任何帮助,我将不胜感激。

我确定这是一个愚蠢的错误,只是我没有看到

我的错误代码

Description:

Parameter 0 of constructor in com.example.demo.jwt.JwtSecretKey required a bean of type 'com.example.demo.jwt.JwtConfig' that could not be found.


Action:

Consider defining a bean of type 'com.example.demo.jwt.JwtConfig' in your configuration.

JwtSecretKey class

package com.example.demo.jwt;

import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.crypto.SecretKey;

@Configuration
public class JwtSecretKey {

  private final JwtConfig jwtConfig;

  @Autowired
  public JwtSecretKey(JwtConfig jwtConfig) {
    this.jwtConfig = jwtConfig;
  }

  @Bean
  public SecretKey secretKey() {
    return Keys.hmacShaKeyFor(jwtConfig.getSecretKey().getBytes());
  }
}

JwtConfig class

package com.example.demo.jwt;

import com.google.common.net.HttpHeaders;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "application.jwt")
public class JwtConfig {

  private String secretKey;
  private String tokenPrefix;
  private Integer tokenExpirationAfterDays;

  public JwtConfig() {}

  public String getSecretKey() {
    return secretKey;
  }

  public void setSecretKey(String secretKey) {
    this.secretKey = secretKey;
  }

  public String getTokenPrefix() {
    return tokenPrefix;
  }

  public void setTokenPrefix(String tokenPrefix) {
    this.tokenPrefix = tokenPrefix;
  }

  public Integer getTokenExpirationAfterDays() {
    return tokenExpirationAfterDays;
  }

  public void setTokenExpirationAfterDays(Integer tokenExpirationAfterDays) {
    this.tokenExpirationAfterDays = tokenExpirationAfterDays;
  }

@Configuration

注释您的 JwtConfig class
@Configuration
@ConfigurationProperties(prefix = "application.jwt")
public class JwtConfig {

参见 Javadocs:

Annotation for externalized configuration. Add this to a class definition or a @Bean method in a @Configuration class if you want to bind and validate some external Properties (e.g. from a .properties file).

参考:https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/properties/ConfigurationProperties.html