gpt4 book ai didi

java - Spring Boot Configuration 类无法在运行时连接 ConfigurationProperties

转载 作者:行者123 更新时间:2023-12-02 01:38:03 24 4
gpt4 key购买 nike

这里是 Java 8 和 Spring Boot 1.5.8。我有以下application.properties文件:

logging:
config: 'logback.groovy'
myapp:
hystrixTimeoutMillis: 500
jwt:
expiry: 86400000
secret: 12345
machineId: 12345
spring:
cache:
type: none

映射到以下@ConfigurationProperties POJO:

@ConfigurationProperties(prefix = "myapp")
public class MyAppConfig {
private Jwt jwt;
private Long hystrixTimeoutMillis;
private String machineId;

public Jwt getJwt() {
return jwt;
}

public void setJwt(Jwt jwt) {
this.jwt = jwt;
}

public Long getHystrixTimeoutMillis() {
return hystrixTimeoutMillis;
}

public void setHystrixTimeoutMillis(Long hystrixTimeoutMillis) {
this.hystrixTimeoutMillis = hystrixTimeoutMillis;
}

public String getMachineId() {
return machineId;
}

public void setMachineId(String machineId) {
this.machineId = machineId;
}

public static class Jwt {
private Long expiry;
private String secret;

public Long getExpiry() {
return expiry;
}

public void setExpiry(Long expiry) {
this.expiry = expiry;
}

public String getSecret() {
return secret;
}

public void setSecret(String secret) {
this.secret = secret;
}
}
}

我有以下@Configuration (注入(inject)器)类:

@Configuration
public class MyAppInjector implements ApplicationContextAware {
private Logger log = LoggerFactory.getLogger(this.getClass());

private ApplicationContext applicationContext;

@Autowired
private MyAppConfig myAppConfig;

@Bean
public AuthService authService(MyAppConfig myAppConfig) {
return new JwtAuthService(myAppConfig);
}
}

以及以下JwtAuthService类:

public class JwtAuthService implements AuthService {
private static final String BEARER_TOKEN_NAME = "Bearer";

private Logger log = LoggerFactory.getLogger(this.getClass());

private MyAppConfig myAppConfig;

@Autowired
public JwtAuthService(MyAppConfig myAppConfig) {
this.myAppConfig = myAppConfig;
}

@Override
public boolean isValidAuthToken(String authToken) {
return true;
}
}

启动时出现以下错误:

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

Description:

Field myAppConfig in com.example.myapp.spring.MyAppInjector required a bean of type 'com.example.myapp.spring.MyAppConfig' that could not be found.

Action:

Consider defining a bean of type 'com.example.myapp.spring.MyAppConfig' in your configuration.

为什么我会收到此错误?我在哪里注入(inject)/配置不正确?

最佳答案

您没有在示例中的任何位置将 MyAppConfig 声明为 bean,@ConfigurationProperties 不会使带注释的类成为 bean。您可以将其作为 MyAppInjector 配置的一部分来执行:

@Configuration
public class MyAppInjector {

@Bean
public AuthService authService() {
return new JwtAuthService(myAppConfig());
}

@Bean
public MyAppConfig myAppConfig() {
return new MyAppConfig();
}

}

关于java - Spring Boot Configuration 类无法在运行时连接 ConfigurationProperties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54911734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com