Hi,
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:
Code:@Bean(initMethod="init") 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
then spring doesn't call the init method.Code:@Bean(initMethod="init", name="XLSExportImpl")
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:
Unfortunately that doesn't exist.Code:@Component( initMethod="init")
Is using a separate Configurable class or XML defn file really the only way possible to accomplish this? What is the best-practice method?
Thanks,
Eric


Reply With Quote
