1

I’m using Spring 3.2.11.RELEASE. I have a class (annotated with @Service), in which I have a method

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 />. 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? I don’t care if its @PostConstruct, if there’s another way or annotation i need. that. The key thing is that the method have access to autowired Spring beans.

mattias
  • 2,079
  • 3
  • 20
  • 27
Dave
  • 15,639
  • 133
  • 442
  • 830
  • First question, is your bean getting autowired? Coz i doubt thats happening – Pratik Apr 30 '15 at 21:16
  • Sure is, is the answer. – Dave Apr 30 '15 at 21:33
  • With the above provided information its hard to tell what the problem is with the post construct. Can you post some more of your service class. Does it have `@transactional` annotation etc? – minion May 01 '15 at 14:57

2 Answers2

0

Could you use Spring's aop (Aspect Orientation) functionality?

<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

Lydia Ralph
  • 1,455
  • 1
  • 17
  • 33
0

What I did instead was implement the "InitializingBean " interface ...

implements InitializingBean 

and overriding the "afterPropertiesSet" method solved my problem.

Dave
  • 15,639
  • 133
  • 442
  • 830