IT story

spring-boot-starter-web을 사용하여“적용 가능한 표현을 찾을 수 없습니다”

hot-time 2020. 12. 30. 19:14
반응형

spring-boot-starter-web을 사용하여“적용 가능한 표현을 찾을 수 없습니다”


spring-boot-starter-webJava 개체의 JSON 표현을 제공하는 나머지 서비스를 만드는 데 사용하려고 합니다. 이 boot-starter-web jar는 Jackson을 통해 JSON으로의 변환을 자동으로 처리해야하지만 대신이 오류가 발생합니다.

{ "timestamp": 1423693929568,
  "status": 406,
  "error": "Not Acceptable",
  "exception": "org.springframework.web.HttpMediaTypeNotAcceptableException",
  "message": "Could not find acceptable representation"
}

내 컨트롤러는 이거 ...

@RestController
@RequestMapping(value = "/media")
public class MediaController {
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public @ResponseBody UploadResult test(@RequestParam(value="data") final String data) {
      String value = "hello, test with data [" + data + "]"; 
      return new UploadResult(value);
    }

    @RequestMapping(value = "/test2", method = RequestMethod.POST)
    public int test2() {
        return 42;
    }

    @RequestMapping(value = "/test3", method = RequestMethod.POST)
    public String test3(@RequestParam(value="data") final String data) {
        String value = "hello, test with data [" + data + "]"; 
        UploadResult upload = new UploadResult(value);
        return upload.value;
    }


    public static class UploadResult {
        private String value;
        public UploadResult(final String value)
        {
            this.value = value;
        }
    }
}

pom.xml...

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>1.2.1.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <version>1.2.1.RELEASE</version>
        <scope>provided</scope>
    </dependency>

mvn dependency:tree spring-boot-starter-web이 실제로 jackson2.4 데이터 바인딩에 의존하므로 클래스 경로에 있어야 함을 보여줍니다.

[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.2.1.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:1.2.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:1.2.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.2.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.2.1.RELEASE:compile
[INFO] |  |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.8:compile
[INFO] |  |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.8:compile
[INFO] |  |  \- org.yaml:snakeyaml:jar:1.14:runtime
[INFO] |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.4.4:compile
[INFO] |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.4.0:compile
[INFO] |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.4.4:compile
[INFO] |  +- org.hibernate:hibernate-validator:jar:5.1.3.Final:compile
[INFO] |  |  +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] |  |  +- org.jboss.logging:jboss-logging:jar:3.1.3.GA:compile
[INFO] |  |  \- com.fasterxml:classmate:jar:1.0.0:compile
[INFO] |  +- org.springframework:spring-web:jar:4.1.4.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-aop:jar:4.1.4.RELEASE:compile
[INFO] |  |  |  \- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  |  +- org.springframework:spring-beans:jar:4.1.4.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-context:jar:4.1.4.RELEASE:compile
[INFO] |  \- org.springframework:spring-webmvc:jar:4.1.4.RELEASE:compile
[INFO] |     \- org.springframework:spring-expression:jar:4.1.4.RELEASE:compile

...하지만 test서비스를 호출하면 위에서 언급 한 오류가 발생합니다. test2그리고 test3잘 작동은 그냥 실패 JSON을 시도 변환해야합니다 것을 증명? 일부 구성 문제 또는 주석이 누락 되었습니까? 내가 찾을 수있는 모든 예제에서 기본 Jackson JSON 변환을위한 클래스에 주석을 달 필요가 더 이상 필요하지 않습니다.

어떤 도움이라도 대단히 감사합니다.


UpdateResult에 대한 공개 getter가 없습니다. 예 :

public static class UploadResult {
    private String value;
    public UploadResult(final String value)
    {
        this.value = value;
    }

    public String getValue() {
       return this.value;
    }
}

기본적으로 자동 검색이 켜져 있으며 게터를 검색하려고 시도합니다. 을 사용하여 비활성화 할 수 있으며 @JsonAutoDetect(getterVisibility=Visibility.NONE)예제에서는 [].


내가 사용 유사한 오류했다 spring/jhipsterRESTful 서비스를 (통해 Postman)

끝점은 다음과 같습니다.

@RequestMapping(value = "/index-entries/{id}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<IndexEntry> getIndexEntry(@PathVariable Long id) {

I was attempting to call the restful endpoint via Postman with header Accept: text/plain but I needed to use Accept: application/json


I too was facing a similar issue. In my case the request path was accepting mail id as path variable, so the uri looked like /some/api/test@test.com

And based on path, Spring determined the uri is to fetch some file with ".com" extension and was trying to use different media type for response then intended one. After making path variable into request param it worked for me.


My return object didn't have @XmlRootElement annotation on the class. Adding the annotation solved my issue.

@XmlRootElement(name = "ReturnObjectClass")
public class ReturnObjectClass {

    @XmlElement(name = "Status", required = true)
    protected StatusType status;
    //...
}

If using @FeignClient, add e.g.

produces = "application/json"

to the @RequestMapping annotation


Add Below dependency :

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.4.6</version>
</dependency>

I had to explicitly call out the dependency for my json library in my POM.

Once I added the below dependency, it all worked.

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

accepted answer is not right with Spring 5. try changing your URL of your web service to .json! that is the right fix. great details here http://stick2code.blogspot.com/2014/03/solved-orgspringframeworkwebhttpmediaty.html


I had the same exception but the cause was different and I couldn't find any info on that so I will post it here. It was just a simple to overlook mistake.

Bad:

@RestController(value = "/api/connection")

Good:

@RestController
@RequestMapping(value = "/api/connection")

In my case I happened to be using lombok and apparently there are conflicts with the get and set


Add @Data annotation over the pojo class which you want to deserialize. The issue is solved for me :)

For example,

    import lombok.Data;

    @Data
    public class Response {
    private Integer status;
    private String type;
    }

I had this issue when accessing actuator. Putting following configuration class solved the issue:

@Configuration
@EnableWebMvc
public class MediaConverterConfiguration implements WebMvcConfigurer {
    @Bean
    public MappingJackson2HttpMessageConverter jacksonConverter() {
        MappingJackson2HttpMessageConverter mc =
                new MappingJackson2HttpMessageConverter();
        List<MediaType> supportedMediaTypes =
                new ArrayList<>(mc.getSupportedMediaTypes());
        supportedMediaTypes
                .add(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE));
        supportedMediaTypes.add(
            MediaType.valueOf("application/vnd.spring-boot.actuator.v2+json"));
        mc.setSupportedMediaTypes(supportedMediaTypes);
        return mc;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(jacksonConverter());
    }
}

I had the same exception. The problem was, that I used the annotation

@RepositoryRestController

instead of

@RestController

ReferenceURL : https://stackoverflow.com/questions/28466207/could-not-find-acceptable-representation-using-spring-boot-starter-web

반응형