简体   繁体   English

初始化bean时如何让Spring执行方法?

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

I'm using Spring 3.2.11.RELEASE. 我正在使用Spring 3.2.11.RELEASE。 I have a class (annotated with @Service ), in which I have a method 我有一个类(用@Service注释),在其中有一个方法

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

However, this method is never getting called, despite the fact the service class is included in a <context:component-scan /> . 但是,尽管服务类包含在<context:component-scan /> ,但从未调用此方法。 I have this in my application context file … 我的应用程序上下文文件中有这个……

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

How do I get a method to be executed when my bean is created/initialized? 创建/初始化bean时,如何获取要执行的方法? I don't care if its @PostConstruct , if there's another way or annotation i need. 我不在乎它的@PostConstruct ,是否还有我需要的另一种方式或注释。 that. 那。 The key thing is that the method have access to autowired Spring beans. 关键是该方法可以访问自动装配的Spring Bean。

Could you use Spring's aop ( Aspect Orientation ) functionality? 您可以使用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>

You'll need to include xmlns:aop="http://www.springframework.org/schema/aop 您需要包含xmlns:aop="http://www.springframework.org/schema/aop

What I did instead was implement the "InitializingBean " interface ... 相反,我要做的是实现“ InitializingBean”接口...

implements InitializingBean 

and overriding the "afterPropertiesSet" method solved my problem. 并覆盖“ afterPropertiesSet”方法解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM