【问题标题】:Spring : how to replace constructor-arg by annotation? [duplicate]Spring:如何通过注释替换构造函数参数? [复制]
【发布时间】:2012-11-23 09:25:49
【问题描述】:

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

谢谢。

【问题讨论】:

    标签: java spring annotations


    【解决方案1】:

    我想你想要的是这样的:

    @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${} 语法读取系统属性。

    为此,您可以在 @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
    

    【讨论】:

    • 太棒了!谢谢你:)
    • 是时候切换到 groovy 配置了
    猜你喜欢
    • 2012-06-17
    • 2016-01-07
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多