Search code examples
javaspringjavabeans

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.


Solution

  • Use the attribute ref, if you want to refer to another Spring bean:

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