繁体   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