简体   繁体   中英

how to configure spring beans with null return in context xml file

is there a way if we can convert below java bean in spring xml

@Bean(name = "tls")
public SslContextFactory getSslContextFactory() {
    return null;
}

i tried setting up like below

<bean id="tls" class="abc.SslContextFactory"/>

but it returns me an object with all the values set as null. However, above java bean works fine and returns null as expected. I tried setting up as below,

<bean id="tls" class="abc.SslContextFactory">
<null/>
</bean>

but it is syntactically wrong.

i am a newbie in spring and working on multiple experiments to understand more about spring. any suggestion is appreciated :)

If you are simply autowiring this bean somewhere, you can use like this -

@Autowired(required = false)
private SslContextFactory tls;

Also, you won't have to declare anything in xml. @Autowired(required = false) will set it to null if no bean definition is found.

You need to use spring FactoryBean.

public class SslContextNullFactory  implements FactoryBean<Void> {

    public Void getObject() throws Exception {
        return null;
    }

    public Class<? extends Void> getObjectType() {
        return null;
    }

    public boolean isSingleton() {
        return true;
    }
}

And

<bean id="tls" class = "abc.SslContextNullFactory" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM