简体   繁体   English

不确定Spring bean中构造函数args的概念

[英]unsure of concept of constructor args in spring beans

after watching various tutorials and doing some reading I understand how to use constructor arguments in spring. 看完各种教程并阅读后,我了解了如何在春季使用构造函数参数。 no issue there. 那里没有问题。 my issue is can someone explain or point me to some material where it explains WHY they are used. 我的问题是有人可以向我解释或指出某些资料来解释为什么使用它们。 what I mean by that, surely with syntax like this: <constructor-arg value="threading"></constructor-arg> , a hardcoded value is poor practice? 我的意思是,肯定是这样的语法: <constructor-arg value="threading"></constructor-arg> ,硬编码的值是不好的做法吗? i dont want an any articles on spring concerning how to do it. 我不想在春季发表任何有关如何做的文章。 i just need a simple answer to explain why hardcoding is seemingly okay here OR better solutions. 我只需要一个简单的答案即可解释为什么硬编码在这里看起来还可以,还是更好的解决方案。 I am aware of the @Resource annotation which gets rid of the need for lines such as <property name="answer" ref="answer"></property> but I have always been taught hardcoding is bad idea and pulling from a DB for example is a better solution 我知道@Resource批注摆脱了对诸如<property name="answer" ref="answer"></property>但是我一直被教导硬编码是一个坏主意,并且是从数据库中提取的例如是更好的解决方案

<bean id="questions" class="main.Questions">
        <constructor-arg value="0000"></constructor-arg>
        <constructor-arg value="What is the question?"></constructor-arg>
        <constructor-arg value="threading"></constructor-arg>
        <property name="correctAnswer" value="deadlock"></property>

</bean>

This is not hard coding... It took me a bit to figure out what you meant, but check out this wiki article: 这不是硬编码...花了我一些时间才能弄清您的意思,但请查看以下Wi​​ki文章:

http://en.wikipedia.org/wiki/Hard_coding http://zh.wikipedia.org/wiki/硬编码

You are not hard coding by providing constructor/property injection values as literals in an XML, because the XML serves as an externalized data source. 通过将构造函数/属性注入值作为XML中的文字提供,您并不是很难进行编码,因为XML用作外部数据源。 Practically this is no different from a value in a field in a DB someplace. 实际上,这与某个数据库中某个字段中的值没有什么不同。 If you modify it in the XML, you dont need to recompile your code to make it work. 如果在XML中修改它,则无需重新编译代码即可使其工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM