Spring:如何通过注释替换构造函数参数? [英] Spring : how to replace constructor-arg by annotation?

查看:50
本文介绍了Spring:如何通过注释替换构造函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
替换带有Spring注解

我想用注释替换 XML applicationContext 配置.

i would like to replace an XML applicationContext configuration by an annotation.

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

How to replace a simple bean with constructor arguments which are fixed ?

示例:

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

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

I'm reading some explanation on @Value, but i don't really understand how to pass some fixed values...

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

Is it possible to load this bean when the web application is deployed ?

谢谢.

推荐答案

我认为你所追求的是:

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

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

You also might want these files to be configurable via system properties. You can use the @Value annotation to read system properties using the PropertyPlaceholderConfigurer, and the ${} syntax.

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

To do this, you can use different String values in your @Value annotation:

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

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

but you will also need these properties in your system properties:

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

这篇关于Spring:如何通过注释替换构造函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆