views:

196

answers:

1

Hi,

We're building a ThreadFactory so everytime a singleton controller needs a new thread, i get a new instance everytime.

Looking at Lookup method injection looks good but what if we have multiple thread classes? I like the fact that i can autowire my threadBeans.

like:

public abstract class ThreadManager {
        public abstract Thread createThreadA();
        public abstract Thread createThreadB();
}

and config:

<bean id="threadManager" class="bla.ThreadManager" singleton="true">
    <lookup-method name="createThreadA" bean="threadA" />
    <lookup-method name="createThreadB" bean="threadB"/>
</bean>
<!-- Yes! i can autowire now :)-->
<bean id="threadA" class="bla.ThreadA" singleton="false" autowire="byType">
<bean id="threadB" class="bla.ThreadB" singleton="false" autowire="byType">

and usage:

threadManager.createThreadA();

Question: I don't want to create an abstract "create" method for every new threadclass.

Is it possible to make this generich like:

threadManager.createThread(ThreadA.class);

I also looked at ServiceLocatorFactoryBean but for multiple classes i have to pass the bean name (not type safe). Thank you

+1  A: 

I don't think there is a way to do that automatically. And if you don't want to use ExecutorService, as suggested, you you can achieve this manually, if it is such a problem for you (but I don't think it is)

  • make your threadManager implement ApplicationContextAware or BeanFactoryAware, thus obtaining the application context / bean factory
  • in your createThread(..) method use the context/factory obtained above to get an instance of the thread bean (which should be of scope prototype of course)
Bozho
Thank you but that's not the problem i described in my question.
Michael Bavin
Why do you think it isn't?
Bozho
You want me not using IOC and call a getbean()?
Michael Bavin
Yes. But that's what the lookup-method is actually doing anyway. It will just be your custom lookup-method
Bozho
This way i also don't have type safety. i'd like to pass the class, but getbean() wants a bean name.
Michael Bavin
look around the other methods there - you can list all beans and get the one with the appropriate class.
Bozho