2010-09-17 55 views
19

我對Spring有點新(使用3.0),所以我希望有一個簡單的答案。如果我有一個註釋爲@Controller@RequestMapping的控制器,並且我想通過依賴注入來設置屬性,那麼我該怎麼做?控制器類不必出現在Spring配置文件中,因爲它由@Controller註釋自動拾取。如何將一個bean注入@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; 
    } 
} 

Spring配置:

<?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> 

這個工作過程是,但我想注入 「XXX」 屬性。我該如何去做呢?

+0

請參考[春天依賴注入使用基於註釋的自動裝配](http://opensourceforgeeks.blogspot.in/2015/11/spring-dependency-injection-using.html) – 2016-09-29 11:52:29

回答

25
@Autowired 
private YourService yourServiceBean; 

(你也可以使用@Inject

當然,YourService都將被聲明爲豆 - 無論是在applicationContext.xml,或註釋(@Service例如)

如果你想注入字符串屬性,您可以使用@Value註釋:

@Value("${propName}") 
private String str; 

(對於您西港島線我需要一個PropertyPlaceholderConfigurer

+0

謝謝。如果我只是想注入一個值爲「hello」的String,它將如何看待applicationContext.xml文件? – GriffeyDog 2010-09-17 13:50:25

+0

@GriffeyDog見更新 – Bozho 2010-09-17 13:53:26

+1

謝謝,完美! – GriffeyDog 2010-09-17 13:55:17

相關問題