I know it’s a problem that is been posted 100 times, but unfortunately I am getting a Defining Bean
error in my Spring Boot
Application and I really do not know why. I do not see my error from launch to finish since I am defining a bean.
I would appreciate any help.
I’m sure it’s a stupid mistake which I just don’t see
My error Code
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; }
Advertisement
Answer
Annotate your JwtConfig
class with @Configuration
@Configuration @ConfigurationProperties(prefix = "application.jwt") public class JwtConfig {
See in 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).