【问题标题】:Configuring Spring 4 MVC Controller配置 Spring 4 MVC 控制器
【发布时间】:2016-02-19 09:53:08
【问题描述】:

我正在尝试学习用于 Restful Web 服务的 Spring 4 MVC 的基础知识,但这不是这里的问题。

在我的@RestController 中,我想使用 Spring 的 Unmarshaller 接口,特别是使用 Jaxb2Marshaller。所以,就目前而言,我有....

@RestController
@RequestMapping("/postuser")
public class MyController {
    private String xsdFileName = "User.xsd";
    private Jaxb2Marshaller unmarshaller;

    public MyController() {
        unmarshaller = new Jaxb2Marshaller();
        unmarshaller.setPackagesToScan("com.mypackage");
    }
// rest of class
}

有效。但是我如何通过@Autowired 设置解组器或通过 XML 配置文件使用 Spring 的依赖注入来做同样的事情呢?

我的 dispatcher-servlet.xml 文件很简单...

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:p="http://www.springframework.org/schema/p"
      xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

   <context:component-scan base-package="com.mypackage" />

   <mvc:annotation-driven />

 </beans>

非常感谢您的帮助和建议。

克里斯

【问题讨论】:

  • 您真的需要将编组器自动连接到控制器中吗?这些通常的用法就像“不工作”部分中的stackoverflow.com/questions/26070566/…(我想现在可以工作了)。用 MVC 注册它们,然后让 spring 自动使用它们来编组所有 XML 请求。
  • zapl:不,我不必让编组器自动连线。这只是我想到的一种配置方式。 Spring 有几种配置方式——我不确定如何正确地将 Marshaller 注入到 Controller 中,而不仅仅是硬编码。

标签: java spring spring-mvc


【解决方案1】:

你可以使用配置类

@Configuration
public MyClass{

    @Bean
    public Jaxb2Marshaller unmarshaller() {
        Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller();
        unmarshaller.setPackagesToScan("com.mypackage");
        return unmarshaller;
    }
}

然后在你的控制器中

@RestController
@RequestMapping("/postuser")
public class MyController {
    private String xsdFileName = "User.xsd";
    @Autowired
    private Jaxb2Marshaller unmarshaller;

// rest of class
}

你也可以在xml文件中定义bean

<bean id="unmarshaller" class="package.Jaxb2Marshaller">
    <property name="packagesToScan">
        <value>com.mypackage</value>
    </property>
</bean>

【讨论】:

  • 那行得通。谢谢。不过我很好奇,你会如何在 XML 文件中做同样的事情?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-11
  • 2014-06-01
  • 1970-01-01
  • 2017-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多