问题 Spring:如何通过注释替换constructor-arg? [重复]


可能重复:
用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?

谢谢。


9927
2017-12-05 14:14


起源



答案:


我想你所追求的是:

@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

13
2017-12-05 14:20



很棒!谢谢 :) - MychaL
时间切换到groovy配置 - vach


答案:


我想你所追求的是:

@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

13
2017-12-05 14:20



很棒!谢谢 :) - MychaL
时间切换到groovy配置 - vach