Gri*_*Dog 20 java spring spring-mvc
我对Spring(使用3.0)有些新意,所以我希望有一个简单的答案.如果我有一个带有@Controller和的注释控制器,@RequestMapping并且我想通过依赖注入设置属性,我该如何去做呢?控制器类不必出现在Spring配置文件中,因为它会因@Controller注释而自动拾取.
示例控制器类:
package gov.wi.dnr.wh.web.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class RehabHomeController {
private String xxx;
@RequestMapping(value="/rehab/home", method = RequestMethod.GET)
public String get() {
return "whdb.rehabhome";
}
public String getXxx() {
return xxx;
}
public void setXxx(String xxx) {
this.xxx = xxx;
}
}
Run Code Online (Sandbox Code Playgroud)
弹簧配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<context:component-scan base-package="gov.wi.dnr.wh.web.spring"/>
<mvc:annotation-driven />
</beans>
Run Code Online (Sandbox Code Playgroud)
这是按原样工作,但我想注入"xxx"属性.我该怎么做呢?
Boz*_*zho 28
@Autowired
private YourService yourServiceBean;
Run Code Online (Sandbox Code Playgroud)
(你也可以用@Inject)
当然,YourService必须声明为bean - 无论是在文本中applicationContext.xml还是通过注释(@Service例如)
如果要注入字符串属性,可以使用@Value注释:
@Value("${propName}")
private String str;
Run Code Online (Sandbox Code Playgroud)
(为此你需要一个PropertyPlaceholderConfigurer)
| 归档时间: |
|
| 查看次数: |
21170 次 |
| 最近记录: |