簡體   English   中英

初始化bean時如何讓Spring執行方法?

[英]How to get Spring to execute a method when the bean is initialized?

我正在使用Spring 3.2.11.RELEASE。 我有一個類(用@Service注釋),在其中有一個方法

package org.mainco.subco.myproject.service;
…
@PostConstruct
public void initCaches()
{
    LOG.info("initiating caches.");
    …
}   // initCaches

但是,盡管服務類包含在<context:component-scan /> ,但從未調用此方法。 我的應用程序上下文文件中有這個……

<context:component-scan base-package="org.mainco.subco" />

創建/初始化bean時,如何獲取要執行的方法? 我不在乎它的@PostConstruct ,是否還有我需要的另一種方式或注釋。 那。 關鍵是該方法可以訪問自動裝配的Spring Bean。

您可以使用Spring的aopAspect Orientation )功能嗎?

<aop:config>
   <aop:aspect ref="service">
      <aop:pointcut id="myotherbeans" 
         expression="execution(* package.name.myotherbeans.initializers(...))"
      />
      <aop:before
         pointcut-ref="myotherbeans"
         method="initCaches" 
      />
   </aop:aspect>
</aop:config>

您需要包含xmlns:aop="http://www.springframework.org/schema/aop

相反,我要做的是實現“ InitializingBean”接口...

implements InitializingBean 

並覆蓋“ afterPropertiesSet”方法解決了我的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM