gpt4 book ai didi

java - Spring : how to replace constructor-arg by annotation?

转载 作者:IT老高 更新时间:2023-10-28 13:56:51 29 4
gpt4 key购买 nike

Possible Duplicate:
replace <constructor-arg> with Spring Annotation

我想用注解替换 XML applicationContext 配置。

如何用固定的构造函数参数替换一个简单的bean?

示例:

<bean id="myBean" class="test.MyBean">
<constructor-arg index="0" value="$MYDIR/myfile.xml"/>
<constructor-arg index="1" value="$MYDIR/myfile.xsd"/>
</bean>

我正在阅读关于@Value 的一些解释,但我不太明白如何传递一些固定值...

是否可以在部署 Web 应用程序时加载此 bean?

谢谢。

最佳答案

我想你想要的是这样的:

@Component
public class MyBean {
private String xmlFile;
private String xsdFile;

@Autowired
public MyBean(@Value("$MYDIR/myfile.xml") final String xmlFile,
@Value("$MYDIR/myfile.xsd") final String xsdFile) {
this.xmlFile = xmlFile;
this.xsdFile = xsdFile;
}

//methods
}

您可能还希望这些文件可以通过系统属性进行配置。您可以通过 PropertyPlaceholderConfigurer${} 语法使用 @Value 注释来读取系统属性。

为此,您可以在 @Value 注释中使用不同的 String 值:

@Value("${my.xml.file.property}")
@Value("${my.xsd.file.property}")

但您的系统属性中还需要这些属性:

my.xml.file.property=$MYDIR/myfile.xml
my.xsd.file.property=$MYDIR/myfile.xsd

关于java - Spring : how to replace constructor-arg by annotation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13725165/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com