In CDI decoratos cannot be injected/obtained directly. Instead, you should always obtain the bean which is being decorated (i.e. something similar to the code in the comment). However, the method
MovieListerSortedDecorator#getGetMovies()looks pretty odd. It's an instance method and you're using CDI SE bootstrap API to start a CDI container there. What exactly are you trying to achieve?
ive got a GUI which reads Directors and u can query through the directors names and see all their movies
the GUI needs an GetMovies
object to do that
getGetMovies is in another class and no part of MovieListerSortedDecorator
MovieLister returns unsorted list's and the MovieListerSortedDecorator returns the list sorted (i know that all of this (the architecture) makes no sense but its for school and this architecture is required)
how can i return an MovieListerSortedDecorator in getGetMovies? (or how can i add the MovieListerSortedDecorator func. to a MovieLister?)
// I know how the Decorator Pattern works and i can implement it without Weld, but im stuck implementing it with Weld
Another note - you are enabling your decorator via both, beans.xml and @Priority.
You should only choose one way (for you @Priority is the go-to option I woud say).
Otherwise, like Martin said, decorators and not to be injected directly, the automatically affect beans with given type (that's what the @Delegate is for).
Hence all calls to those beans will in fact invoke decorator first - which is exactly what you want.
Last but not least, the way you start CDI container is pretty awkward - you only boot to it grab that one bean and immediately close it.
If you wish to use CDI throughout your application, you should boot it once the application starts and shut it down when it exits - CDI container should be running in the meantime.
Here are some reasons why, just from the top of my head:
- Re-booting is expensive and gets even more expensive the more beans you have (scanning, instantiating, events,...)
- When you re-boot, everything goes from scratch, you loose all the context/state/beans you had (it's unlikely this is desired behaviour)
- Using a previously retrieved instance of a bean after you close the CDI container will likely give you exceptions (CDI no longer "lives" hence you are effectively holding a handle to dead instance so to speak)
Beware - the decorator pattern, as defined by GoF, or as defined on Wiki, is not 1-to-1 with what CDI has. It's similar but not the same.
In CDI, you don't want to grab an instance of decorator directly, instead you grab the bean you defined in the first place (GetMovies) and if you invoke a method on that bean, it will automatically invoke decorator since it's applied to it.
Therefore you just do:
MovieLister ml = container.select(MovieLister.class).get(); // grab the bean ml.getAllDirectors(); // this call will in fact automatically invoke MovieListerSortedDecorator.getAllDirectors()