2011-07-02 42 views
1

上訪問它時我正在開發一個帶有Struts2 + Spring + hibernate的小型應用程序...... Spring bean在服務器啓動時被正確注入..我已經在啓動時通過了setter,他們正在注射。但是,我運行post方法,然後執行post方法(struts2中的execute()),並且注入的值爲null。爲什麼會發生?彈簧構造函數注入顯示爲空當在方法

豆注入是:

<bean id="userAction" class="com.example.user.action.UserAction"> 
     <constructor-arg index="0"> 
      <ref bean="UserServiceTarget"/> 
     </constructor-arg> 
</bean> 

我Struts2的構造函數是:

public UserAction(IUserService userService) 
    { 
     this.userService=userService; 

    } 

Struts2的方法是:

public String execute() { 
     this.user=(User)userService.findById(this.id); 
} 

但是這裏面execute方法userService值爲空...當我注射他們是精心注射..

謝謝...

+1

另外,你可以編輯問題並添加完整的UserAction類和完整的上下文嗎? – andyb

回答

2

我認爲構造函數參數不是將bean彈出到另一個的方式。我給你舉個例子:

的applicationContext.xml:

<bean id="userAction" class="com.example.user.action.UserAction"/> 
<bean id="userServiceTarget" class="com.example.user.UserServiceTarget"> 

UserAction.java:

@Autowired 
private UserServiceTarget userService; 

您可以使用其他配置也。 例如:

<bean id="userAction" class="com.example.user.action.UserAction"> 
<property name="userService" ref="UserServiceTarget"/> 
</bean> 

通過這種方式不需要自動裝配Autowired註解,只是一個二傳手。

我不太喜歡xml,所以最好的方法是使用Stereotype註解。您可以在服務類上使用@Service註解,你可以忘記在appcontext申報豆,但你應該添加兩行是這樣的:

<context:annotation-config /> 

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

希望我幫助!

+0

感謝lepike ....它工作正常...我的問題是我的代碼是什麼錯誤,當我使用構造函數注入... – Muthu

+0

對不起誤解了你。我給你一個解決方法。我不知道你的代碼有什麼問題。構造函數注入也必須工作。 UserServiceTarget的bean定義是什麼?也許你應該檢查bean的id屬性的命名。希望你找到解決方案。 – lepike