java 使用 Spring 将 Boolean bean 创建转换为 boolean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4248057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:30:18  来源:igfitidea点击:

Converting Boolean bean creation to boolean using Spring

javaspringdependency-injectionboolean

提问by AHungerArtist

So, I have something like this in one of my java files:

所以,我的一个 java 文件中有这样的东西:

@Resource(name = "initializationCache")
Boolean initializationCache;

In a config file, I have this:

在配置文件中,我有这个:

<bean id="initializationCache" class="java.lang.Boolean">
    <constructor-arg value="${initialization.cache}" />
</bean>

How would I go about making this work using a primitive boolean?

我将如何使用原始布尔值进行这项工作?

采纳答案by Grzegorz Oledzki

I guess one way to go would be to declare a setter of Booleantype and let it assign the value to a field of booleantype, i.e.

我想一种方法是声明一个Boolean类型的 setter并让它将值分配给一个boolean类型的字段,即

boolean initializationCache;

@Resource(name = "initializationCache")
public void setInitializationCache(Boolean b) {
  this.initializationCache = b;
}

I haven't tested it though.

不过我还没有测试过。

回答by axtavt

In Spring 3 you can do it without intermediate bean using @Value:

在 Spring 3 中,您可以在没有中间 bean 的情况下使用@Value

@Value("${initialization.cache}")
boolean initializationCache;