Spring:如何通过注释替换constructor-arg?

Myc*_*haL 13 java spring annotations

可能重复:
用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>
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢.

nic*_*ild 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
}
Run Code Online (Sandbox Code Playgroud)

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

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

@Value("${my.xml.file.property}")
@Value("${my.xsd.file.property}")
Run Code Online (Sandbox Code Playgroud)

但是您还需要在系统属性中使用这些属性:

my.xml.file.property=$MYDIR/myfile.xml
my.xsd.file.property=$MYDIR/myfile.xsd
Run Code Online (Sandbox Code Playgroud)