13

可能重复:
用 Spring Annotation 替换 <constructor-arg>

我想用注释替换 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?

谢谢你。

4

1 回答 1

17

我想你所追求的是:

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

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

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

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

my.xml.file.property=$MYDIR/myfile.xml
my.xsd.file.property=$MYDIR/myfile.xsd
于 2012-12-05T14:20:41.633 回答