在属性bean上使用@RefreshScope时出现JsonMappingException

时间:2017-09-19 09:57:23

标签: java spring spring-boot spring-cloud

在属性bean 上使用@RefreshScope时出现

JsonMappingException

我有一个spring boot应用程序,它使用spring cloud进行配置

我的配置类如下所示:

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"])

当我从@RefreshScope类中删除MyConfigurationBean注释时,错误会消失,但是当我调用/refresh端点时,bean不会刷新。

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

我遇到了同样的例外情况,发现this answer对问题Casting a Spring's Proxy object to the actual runtime class

基本上RefreshScope在您的原始属性对象上创建一个CGLib代理,该代理无法json序列化。

铸造例如(MyConfigurationBean)((Advised) config).getTargetSource().getTarget()应该可以,但是强烈建议不要这样做。