2012-06-08 59 views
0

我試圖在web應用中實現Spring AOP。不幸的是,我在Web上找到的所有示例代碼都是控制檯應用程序。我正在用盡線索我怎麼能在網絡應用程序中做到這一點?如何將Spring AOP加載到Web應用程序中?

在web.xml文件中,我加載applicationContext.xml的是這樣的:

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>/WEB-INF/applicationContext.xml</param-value> 
</context-param> 

在applicationContext.xml文件,我有ProxyFactryBean是這樣定義的:

<bean id="theBo" class="my.package.TheBo"> 
    ... 
</bean>  
<bean id="theProxy" class="org.springframework.aop.framework.ProxyFactoryBean"> 
     <property name="proxyInterfaces"> 
     <list> 
      <value>my.package.ITheBo</value> 
     </list> 
    </property> 
    <property name="target" ref="theBo"/> 
    <property name="interceptorNames"> 
     <list> 
      <value>loggingBeforeAdvice</value> 
     </list> 
    </property> 
</bean> 

我現在的情況是我不知道哪裏是放置此代碼的最佳位置:

ApplicationContext context = new ClassPathXmlApplicationContext("WEB-INF/applicationContext.xml"); 
theBo = (ITheBo) context.getBean("theProxy"); 

如果這是一個控制檯應用程序,我寧願把它放在main()中,但我怎麼能在web應用程序中做到這一點?

+0

你會將代理連接到一個使用它的類,就像任何其他bean一樣。 –

+0

目前我只有一個bean,它是ITheBo。爲了讓我連接代理,我需要爲Proxy配置另一個bean。我被困在如何將代理投向博弈。 – huahsin68

回答

0

感謝@Dave Newton給我提供了線索。爲了讓我從網上注入theProxy,對於我的情況,這是JSF,我必須在faces-config.xml中輸入以下代碼。

<application> 
    <variable-resolver> 
     org.springframework.web.jsf.DelegatingVariableResolver 
    </variable-resolver> 
</application> 

<managed-bean> 
    <managed-bean-name>theAction</managed-bean-name> 
    <managed-bean-class>org.huahsin68.theAction</managed-bean-class> 
     <managed-bean-scope>session</managed-bean-scope> 
     <managed-property> 
     <property-name>theBo</property-name> 
      <value>#{theProxy}</value> 
     </managed-property> 
</managed-bean> 

及認沽通過提供@湯姆以及進入web.xml聽衆。

3

你不需要下面的代碼加載背景:

ApplicationContext context = new ClassPathXmlApplicationContext("WEBINF/applicationContext.xml"); 
theBo = (ITheBo) context.getBean("theProxy"); 

您必須添加ContextLoaderListenerweb.xml文件:

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

現在,當你的web應用程序啓動將加載<context-param> contextConfigLocation中聲明的上下文。在你的情況'/WEB-INF/applicationContext.xml'。

如果你需要你的上下文在一個特定的類,你可以實現ApplicationContextAware接口來檢索它。

其餘的,你的web應用程序現在是一個基本的彈簧應用程序,你可以像平時一樣連接你的類。

相關問題