【发布时间】:2015-02-03 23:34:15
【问题描述】:
现在我有一个基于 Spring 的 RESTful 网络应用程序。我对 REST 很陌生,所以我在线学习了一些教程。我构建了我的 web.xml、rest-servlet.xml,它使用了组件扫描标签并加载了我的 RestController 类,它使用了 @RestController 注释。 (所有代码贴在下面)
我的问题是这些教程都没有告诉我如何通过 ApplicationContext.xml 将 bean 注入我的控制器。我找到了使用注解注入的方法,但我真的很想使用 xml 配置。在下面的示例中,我有三个数据库客户端,我想在 RestController 启动时连接它们。
有关如何在启动时加载 ApplicationContext.xml 以便我的 RestController servlet 接收数据库客户端的正确实例的任何建议?
web.xml
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
rest-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.helloworld.example" />
<mvc:annotation-driven />
</beans>
RestController.java
package com.helloworld.example;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/service/greeting")
public class SpringServiceController {
@Autowired
DBClient1 dbClient1;
@Autowired
DBClient2 dbClient2;
@Autowired
DBClient3 dbClient3;
@RequestMapping(value = "/{name}", method = RequestMethod.GET)
public String getGreeting(@PathVariable String name) {
String result="Hello "+name + " " dbClient1.toString(); // this is a test to see if the wiring worked
return result;
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dbClient1" class="com.helloworld.example.DBClient1"/>
<bean id="dbClient2" class="com.helloworld.example.DBClient2"/>
<bean id="dbClient3" class="com.helloworld.example.DBClient3"/>
</beans>
【问题讨论】:
标签: java xml spring rest applicationcontext