Search code examples
javawildflyweld

Is it possible to suppress bean injection?


I have an web app which is to be deployed on Wildfly 12. Included in the app is a third party jar with code similar to the following

class X
{
    @Inject private Y y = null;

    public void someMethod()
    {
        if (y == null)
            doSomething();
        else
            doSomethingElse(y);
    }
}

It's clear that the code has been written under the assumption that injection may fail and y can be null.

However Weld doesn't like this and I get a deployment error saying there is a unsatisfied deplendency for y. I can't modify the third party code and I don't want to supply a dependency for y. I would like the doSomething() branch to be taken.

Is it possible to tell Weld not to try and inject anything at this injection point?

Thanks.


Solution

  • Might be overkill, but you can create a producer that always returns null for that class:

    @ApplicationScoped
    public class YProducer {
    
        @Produces
        @RequestScoped  
        public Y create() {
            return null;
        }
    
        public void destroy(@Disposes Y y) {
            //no-op
        }
    }