MAGx2
MAGx2

Reputation: 3189

@Bean method with null parameter

In My usecase sometimes I do have bean MyNullable and sometimes not, what is OK. The problem is when I want to create bean that uses this class (but no always; it will accept null).

in code below if I will not provide bean of class MyNullable I will have error (no finding dependency). Can I somehow annotate this parameter with smthing like required = false link in @Autowired?

@Bean
@Scope(SCOPE_PROTOTYPE)
public SynchronousRpcProxy myBean(MyObj1 notNull1, MyObj2 notNull2, MyNullable canBeNull) {
    assert notNull1 != null;
    assert notNull2 != null;
    // assert canBeNull!= null; // this is not true because canBeNull can be null
    return new SmthFromExternalLib(notNull1, notNull2, canBeNull); // do staff
}

Upvotes: 0

Views: 1511

Answers (2)

Jesper
Jesper

Reputation: 206776

If you are using Java 8 you can use Optional for this:

@Bean
@Scope(SCOPE_PROTOTYPE)
public SynchronousRpcProxy myBean(MyObj1 notNull1, MyObj2 notNull2,
                                  Optional<MyNullable> canBeNull) {
    return new SmthFromExternalLib(notNull1, notNull2, canBeNull.orElse(null));
}

When you do this and there is no MyNullable bean, the Optional will be empty, so that canBeNull.orElse(null) returns null.

If you are not using Java 8, you can create a factory bean that has MyNullable as an optional dependency:

@Component
public class SynchronousRpcProxyFactory
                 implements FactoryBean<SynchronousRpcProxy> {

    @Autowired
    private MyObj1 notNull1;

    @Autowired
    private MyObj1 notNull2;

    @Autowired(required = false)
    private MyNullable canBeNull;

    @Override
    public SynchronousRpcProxy getObject() throws Exception {
        return new SynchronousRpcProxy(notNull1, notNull2, canBeNull);
    }

    @Override
    public Class<?> getObjectType() {
        return SynchronousRpcProxy.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

Upvotes: 2

Damian0o
Damian0o

Reputation: 653

You can try use field in configuration class instead of injecting to factory method

@Autowired(required=false)
MyNullable canBeNull;

Upvotes: 2

Related Questions