Search code examples
javadependency-injectioncdijboss-weld

How to use CDI for method parameter injection?


Is it possible to use CDI to inject parameters into method calls? The expected behaviour would be similar to field injection. The preferred producer is looked up and the product is used.

What I would like to do is this:

public void foo(@Inject Bar bar){
  //do stuff
} 

or this (with less confusing sytax):

public void foo(){
  @Inject 
  Bar bar;
  //do stuff
} 

This syntax is illegal in both cases. Is there an alternative? If no - would this be a bad idea for some reason if it were possible?

Thank you

EDIT - I may have made my requirements not clear enough - I would like to be able to call the method directly, leaving the initialization of the bar variable to the container. Jörn Horstmann's and Perception's answer suggest that it is not possible.


Solution

  • Injection points are processed for a bean when it is instantiated by the container, which does limit the number of uses cases for method level injection. The current version of the specification recognizes the following types of method injection:

    Initializer method injection

    public class MyBean {
        private Processor processor;
    
        @Inject
        public void setProcessor(final Processor processor) {
            this.processor = processor;
        }
    }
    

    When an instance of MyBean is injected, the processor instance will also be injected, via it's setter method.

    Event Observer Methods

    public class MyEventHandler {
        public void processSomeEvent(@Observes final SomeEvent event) {
        }
    }
    

    The event instance is injected into the event handling method directly (though, not with the @Inject annotation)

    Producer Methods

    public class ProcessorFactory {
        @Produces public Processor getProcessor(@Inject final Gateway gateway) {
            // ...
        }
    }
    

    Parameters to producer methods automatically get injected.