Весенние хатеоас с Spring Mvc - PullRequest
0 голосов
/ 02 июля 2018

Я пытаюсь изучить Spring hateoas с помощью Spring MVC, но не могу заставить его работать. Я много гуглил, но все, что я нашел, утешает с Spring Boot У меня очень простой рабочий Spring MVC проект. Мой пом

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.SpringMvcWeb</groupId>
<artifactId>SpringMvcWebXml</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.0.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
<build>
    <finalName>${project.artifactId}</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
</build>

для использования hateaos я добавляю его зависимость

    <dependency>
        <groupId>org.springframework.hateoas</groupId>
        <artifactId>spring-hateoas</artifactId>
        <version>0.24.0.RELEASE</version>
    </dependency>

но его ошибка выдачи общего журнала отсутствует, поэтому я добавляю

<dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>

теперь говорится NoSuchMethodError: org.springframework.web.servlet.handler.AbstractHandlerMapping.obtainApplicationContext ()

что мне не хватает? если бы кто-то мог направить меня к работе Spring MVC и коду hateoas, это было бы очень полезно.

1 Ответ

0 голосов
/ 08 июля 2018

Я пытался воспроизвести ваш вариант использования. на pom.xml должно быть как ниже:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.SpringMvcWeb</groupId>
    <artifactId>SpringMvcWebXml</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
        <javax-jaxb.version>2.3.0</javax-jaxb.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.7.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.hateoas</groupId>
            <artifactId>spring-hateoas</artifactId>
            <version>0.24.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>


        <dependency>
            <groupId>org.springframework.plugin</groupId>
            <artifactId>spring-plugin-core</artifactId>
            <version>1.2.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.6</version>
        </dependency>


    </dependencies>
    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Важнейшая часть - это spring-plugin-core и com.fasterxml.jackson.core, в моем примере я использую json. Мне нужно было ядро ​​Spring-Plugin-Core, потому что Tomcat пропустил этот компонент PluginRegistryFactoryBean.

мой очень простой перевоспитанный сервиз, как показано ниже:

@RestController
public class EndPointSample {

    private final MessageLinkFactory messageLinkFactory;

    public EndPointSample(MessageLinkFactory messageLinkFactory) {
        this.messageLinkFactory = messageLinkFactory;
    }

    @GetMapping("/test")
    public ResponseEntity test(){
        return ResponseEntity.ok(messageLinkFactory.getRes(new Message("hello")));
    }
}

public class MessageLinkFactory {

    public Resource getRes(Message message){
        Link link = linkTo(methodOn(EndPointSample.class).test()).withSelfRel();

        Resource<Message> hello = new Resource<>(message);
        hello.add(link);

        return hello;
    }
}

public class Message {

    private String message;

    public Message() { }

    public Message(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

результат в формате json:

{ message: "hello", _links: {self: { href: "http://localhost:8080/test" } } }

однако это работает, только если вы отправляете запрос с приложением заголовка accetp / hal + json. если вы хотите, чтобы он работал даже с application / json, как при весенней загрузке, вы можете добавить конвертер сообщений для этого. Я положил код, полученный весенней загрузки, которые делают это.

@Component
class HalMessageConverterSupportedMediaTypesCustomizer
        implements BeanFactoryAware {

    private volatile BeanFactory beanFactory;

    @PostConstruct
    public void configureHttpMessageConverters() {
        if (this.beanFactory instanceof ListableBeanFactory) {
            configureHttpMessageConverters(((ListableBeanFactory) this.beanFactory)
                    .getBeansOfType(RequestMappingHandlerAdapter.class).values());
        }
    }

    private void configureHttpMessageConverters(
            Collection<RequestMappingHandlerAdapter> handlerAdapters) {
        for (RequestMappingHandlerAdapter handlerAdapter : handlerAdapters) {
            for (HttpMessageConverter<?> messageConverter : handlerAdapter
                    .getMessageConverters()) {
                configureHttpMessageConverter(messageConverter);
            }
        }
    }

    private void configureHttpMessageConverter(HttpMessageConverter<?> converter) {
        if (converter instanceof TypeConstrainedMappingJackson2HttpMessageConverter) {
            List<MediaType> supportedMediaTypes = new ArrayList<>(
                    converter.getSupportedMediaTypes());
            if (!supportedMediaTypes.contains(MediaType.APPLICATION_JSON)) {
                supportedMediaTypes.add(MediaType.APPLICATION_JSON);
            }
            ((AbstractHttpMessageConverter<?>) converter)
                    .setSupportedMediaTypes(supportedMediaTypes);
        }
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

}

всех этих маленьких шагов должно хватить, чтобы исправить все твои проблемы. Я делаю это, и в моем маленьком POC он работает на tomcat 9.0.x. Я надеюсь, что это может помочь вам

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...