2013-02-26 31 views
3

我正在使用Spring 3.2和Apache Tiles。我使用Roo生成了很多我的服務類。我正在嘗試一個簡單的過程,在jsp模板中注入一個變量。這部分工作正常,但我堅持在我需要引用服務bean的點。Apache Tiles - 無法訪問Spring MVC中的自定義ViewPreparer中的bean

@Component 
public class CustomViewPreparer implements ViewPreparer { 

@Autowired 
UserProfileService ups; 

@Override 
public void execute(TilesRequestContext tilesContext, 
        AttributeContext attributeContext) { 

     Authentication a = SecurityContextHolder.getContext().getAuthentication(); 
     String name = a.getName(); //get logged in username 

     UserProfile up = ups.findByUsername(name); 
     //request.setAttribute("isLoggedIn", up!=null); 

    } 
} 

UserProfileService「ups」始終爲空。我發現這個:http://forum.springsource.org/showthread.php?48950-ViewPreparer-is-triggered-before-Session-starts

但我不明白的迴應。我可以通過在每次返回視圖時注入變量來解決此問題,但我很好奇其他人如何解決此問題。

回答

2

我有同樣的問題,原因是因爲你必須說要從Tiles獲得UserProfileService實例。

所以,你必須這樣做,以顯式地要求使用Spring bean的注射,您的TilesConfigurer:

<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"> 
    <property name="definitions"> 
    <list> 
    ..... 
    </list> 
    </property> 

    <!-- resolving preparer names as Spring bean definition names --> 
    <property name="preparerFactoryClass" 
     value="org.springframework.web.servlet.view.tiles2.SimpleSpringPreparerFactory "/> 

</bean> 

到此處獲取有關CONFIGRATION更多的信息:http://static.springsource.org/spring/docs/2.5.x/reference/view.html

相關問題