MAGx2 MAGx2 - 5 months ago 19
Java Question

@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
}

Answer

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 true;
    }
}