Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
Re: [sisu-users] Accessing a list of components

On 27 February 2014 08:45, Jochen Wiedmann <jochen.wiedmann@xxxxxxxxx> wrote:

Hi,

I've got an interface

  public interface ILifecycleListener() {
    void start();
    void shutdown();
  }

which several of my components implement. The idea is to perform resource alloication and deallocation within these methods.

Now, rather than hard coding the component list into a controller, I'd like to query Sisu, something like

  injector.getComponents(ILifecycleListener.class);

Is that possible? Or, do you have a better idea?

Hi Jochen,

You could either @Inject an Iterable<ILifecycleListener> or a List<ILifecycleListener> ... the injected collection will then contain any implementations of ILifecycleListener bound in the injector (such as @Named classes automatically bound by Sisu). Note that if a given implementation of ILifecycleListener is a @Singleton then you'll see the same instance of that implementation in each injected collection of ILifecycleListener, whereas if it's not a @Singleton then you will see a different instance in each injected collection (but you will see the same instance when repeatedly iterating over the same collection).

You can also get the collection programatically from the BeanLocator if you wish:

   List<ILifecycleListener> components = new EntryListAdapter(locator.locate(Key.get(ILifecycleListener.class)));

There are different adapters for Maps, etc. - or if you want more details about each component then you can use the underlying BeanEntry collection:


-- 
Cheers, Stuart
 
Thanks,

Jochen

--
"That's what prayers are ... it's frightened people trying to make friends with the bully!"

Terry Pratchett. The Last Hero

Back to the top