【发布时间】:2018-02-28 01:27:09
【问题描述】:
在属性 bean 上使用 @RefreshScope 时出现 JsonMappingException
我有一个使用 Spring Cloud 进行配置的 Spring Boot 应用程序
我的配置类如下所示:
package test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
@Component
@EnableConfigurationProperties
@ConfigurationProperties("configuration")
@RefreshScope
public class MyConfigurationBean {
@Value("${configuration.projectName}")
private String name;
private String city;
private int port;
// Getters/setters
}
还有一个看起来像这样的 RESTController:
package test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
public class MyRestController {
@Autowired
private MyConfigurationBean config;
@RequestMapping(value = "/config", produces = MediaType.APPLICATION_JSON_VALUE)
public MyConfigurationBean port() {
return this.config;
}
}
/refresh 端点也已启用。
当我在 /config 上尝试 GET 时,我遇到了这个异常:
2017-09-19 11:46:25.694 WARN 23005 --- [nio-5858-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: No serializer found for class org.springframework.context.expression.StandardBeanExpressionResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.springframework.context.expression.StandardBeanExpressionResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: test.MyConfigurationBean$$EnhancerBySpringCGLIB$$3a7ee0c3["targetSource"]->org.springframework.aop.target.SimpleBeanTargetSource["beanFactory"]->org.springframework.beans.factory.support.DefaultListableBeanFactory["parentBeanFactory"]->org.springframework.beans.factory.support.DefaultListableBeanFactory["beanExpressionResolver"])
当我从MyConfigurationBean 类中删除@RefreshScope 注释时,错误消失了,但是当我调用/refresh 端点时bean 没有刷新。
我的代码有什么问题?
【问题讨论】:
-
因为你在
MyConfigurationBean上放了一堆注释,它是一个代理,它会给你错误。为什么要返回一个配置bean?可能是 DTO 的情况。 -
其实我只是想要一个(Java)Bean,它的属性来自spring cloud config server,可以刷新。
标签: java spring spring-boot spring-cloud