Announcement Announcement Module
No announcement yet.
@Service/@Component Bean autodetection with custom init/constructor methods? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • @Service/@Component Bean autodetection with custom init/constructor methods?


    I've run into a configuration situation and was hoping for some insights as to a best-practice way of doing things.

    Had my bean been a POJO, I would have put a bunch of code in the constructor and been happy with it. However, my constructor would need access to injected members, so I realize that I cannot use a constructor. So that means I need to create an init method.

    The problem is how to configure the bean. Under normal circumstances, I would have just been able to annotate it with @Service or @Component and have it autodetected. With the need for an init method, I find myself in the need of defining the bean configuration:
    	  public XLSExporter xlsExporter() {
    	      return new XLSExporterImpl();

    According to the docs, the @Bean annotation is allowed in any @Component. So I tried to add this within my @Component annotated XLSExporterImpl class, but then autowire complained about having two beans of type XLSExporter: XLSExportImpl (detected from the @Component annotation) and xlsExporter (from the @Bean annotation). If I override the bean name and call it
    	  @Bean(initMethod="init", name="XLSExportImpl")
    then spring doesn't call the init method.

    So it would seem that my only chance is to create a separate @Configurable class with my @Bean annotation to define my bean and specify my init method, and remove the @Component annotation from my class.

    This seems like a lot of overkill (and extra maintenance) when all I wanted was something like:
    @Component( initMethod="init")
    Unfortunately that doesn't exist.

    Is using a separate Configurable class or XML defn file really the only way possible to accomplish this? What is the best-practice method?



  • #2
    Not sure but why not simply annotate your init method with @PostConstruct or let your bean implement InitializingBean (I would go for @PostConstruct)... If all that you want is an init method called after constructing and injection that is all you need to do...


    • #3
      Didn't do that mostly because I didn't realize that the @PostConstruct annotation existed. But after rereading Section 3 of the manual, I noticed it.

      Looks exactly like what I needed.