Spring中根据属性文件动态配置java beans
想知道是否有一种方法可以使用 PropertyPlaceholderConfigurer 类根据属性文件中的值集动态实例化 bean。
我有一个 java bean 说 Student 有两个属性:“name”和“subject”
我有一个属性文件:
student.1.name=student1name
student.1.subject=student1subject
student.2.name=student2name
student.2.name=student2subject
现在我有一个 Classroom 对象,可以获取学生列表。
我想知道是否有一种方法可以使用 Spring 来做到这一点。这里的挑战是学生的数量可能会有所不同。
如果只有一个学生对象,那么:
<bean id="student" class="com.abc.Student">
<property name="name" value="${student.1.name}" />
<property name="subject"
value="${student.1.subject}" />
</bean>
<bean id="classRoom" class="com.abc.ClassRoom">
<property name="student" ref="student" />
</bean>
就会起作用。但在本例中,我们有一个包含 n 个学生的列表。 n 的值可能会根据属性文件中的条目数而变化。
Wondering if there is a way to dynamically instantiate beans based on set of values in your property file using PropertyPlaceholderConfigurer class.
I have a java bean say Student with two attributes: "name" and "subject"
I have a property file with:
student.1.name=student1name
student.1.subject=student1subject
student.2.name=student2name
student.2.name=student2subject
Now I have a Classroom object that can take a list of students.
I am wondering if there is a way we could do this using Spring. The challenge here is that the number of students could vary.
If there was only one student object then:
<bean id="student" class="com.abc.Student">
<property name="name" value="${student.1.name}" />
<property name="subject"
value="${student.1.subject}" />
</bean>
<bean id="classRoom" class="com.abc.ClassRoom">
<property name="student" ref="student" />
</bean>
would have worked. But in this case we have a list of n Students. And the value of n could vary depending on the number of entries in the properties file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我同意凯文——在我看来,你的做法是错误的。
一种可能的解决方法是创建一个 bean,将属性文件作为参数,将其读入,并公开学生列表(需要在 某物 上建立索引,例如 n 在现有属性文件中)。
然后,课堂 Bean 就可以使用该学生列表。
但看起来您确实在尝试以一种尴尬的方式在没有数据库的情况下复制数据库的功能。
I'm with Kevin--IMO you're going about this the wrong way.
One possible workaround would be to create a bean that takes the property file as an argument, reads it in, and exposes a list of students (which would need to be indexed on something, like the n in the existing property file).
The classroom bean could then use that list of students.
But it sure looks like you're trying to duplicate the functionality of a DB, without a DB, in an awkward way.
我认为没有办法使用 PropertyPlaceholderConfigurer 来做到这一点。通常,当我遇到这样的情况时,我会选择 JSON 或 XML 的配置格式,并使用 GSON/Jackson/JAXB 将数据解组为对象。
I don't think there's a way to do that with PropertyPlaceholderConfigurer. Usually when I have a situation like that I choose a configuration format of either JSON or XML and use GSON/Jackson/JAXB to unmarshall the data into objects.