简体   繁体   English

如何将类设置为 bean 中的值?

[英]How do i set a class as a value in beans?

I'm doing my first steps with beans and I want to give the student a hostel, which is also a class.我正在用豆子做我的第一步,我想给学生一个宿舍,这也是一个班级。 What am I doing wrong?我究竟做错了什么?

public class Student {
private String name;
private String id;
private Hostel hostel;
//getters and setters under this

public class Hostel {
private String hostelName;
private String city;
//also getters and setters

beanpart豆瓣

<bean id="student" class="com.tom.demo.Student" autowire="byName">
    <property name="name" value="Sönke Huster"></property>
    <property name="id" value="s81862322B"></property>
</bean>

<bean id="student1" class="com.tom.demo.Student">
    <property name="name" value="Thomas Bruhn"></property>
    <property name="id" value="s8232322"></property>
     <property name="hostel" value="aushos"/>

</bean>

<bean id="hostel" class="com.tom.demo.Hostel">
    <property name="hostelName" value ="Bangladore East Hostel"></property>
    <property name="city" value="Bangladore"></property>
</bean>

<bean id="aushos" class="com.tom.demo.Hostel">
    <property name="hostelName" value ="Easy Go Backpackers"></property>
    <property name="city" value="Sydney"></property>
</bean>

My result is:我的结果是:

Failed to convert property value of type `java.lang.String` to required type `com.tom.demo.Hostel` for property `hostel`; nested exception is `java.lang.IllegalStateException`

I already tried to google or to fix it with casting, but my knowledge is limited.我已经尝试过谷歌或通过铸造修复它,但我的知识有限。 So please help me.所以请帮助我。

如果要引用另一个 Spring bean,请使用属性 ref:

<property name="hostel" ref="aushos"/>

Hostel is a bean here so it should be referred rather than copied.宿舍是这里的豆子,所以应该引用而不是复制。 So use <property name="hostel" ref="aushos"/> "ref" attribute is to refer beans and value attribute is to copy primitive type values.所以使用<property name="hostel" ref="aushos"/> "ref" 属性是引用bean,value 属性是复制原始类型值。

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

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