简体   繁体   English

如何在上下文xml文件中使用null返回值配置spring bean

[英]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 如果我们可以在spring xml中的java bean下面进行转换,有没有办法

@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. 但这会返回一个对象,且所有值都设置为null。 However, above java bean works fine and returns null as expected. 但是,上述java bean可以正常工作,并按预期返回null。 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 - 如果您只是在某个地方自动装配该bean,则可以这样使用-

@Autowired(required = false)
private SslContextFactory tls;

Also, you won't have to declare anything in xml. 另外,您不必在xml中声明任何内容。 @Autowired(required = false) will set it to null if no bean definition is found. 如果未找到任何bean定义,则@Autowired(required = false)会将其设置为null

You need to use spring FactoryBean. 您需要使用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" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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