Reputation: 2103
It might be a very simple question; but since I am a beginner into Spring, I cannot understand how to assign values to Spring beans at the run time.
I followed some tutorials for learning Spring and now I know how to get started with Spring. I can understand the Spring beans.xml
where the bean definition is declared, I can understand some annotations which can be used instead of xml configurations. But I cannot understand how to do the following configuration.
Let's say I have a class called Student. Each student object has a name and an age.
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.address = address;
}
}
This is how will I write the entry in the Beans.xml
file for bean configuration
<bean id="student" class="Student">
<property name="name" value="Joe"></property>
<property name="address" value="12"></property>
</bean>
I am completely okay with this setter injection. As far as I can change the property values using the xml file,I can change the properties of the student.
But let's think we need an application to register students. Using front end form of the application, we enter name and age. My question is how can we inject those name and age values to a Student bean. Now we are dealing with a running application.
I can't understand how should we change the xml to accept the user inputs(if it is the way of doing). In all the beginner tutorials I followed, I didn't find a way to handle such situations. What they teach is what I already know.
I think I am missing some lesson on this. Please guide me to solve my problem. Some example code will be much helpful for me to understand if possible.
Thank You..!
Upvotes: 1
Views: 887
Reputation: 12481
Beans are not suitable for Value Objects, which is why your approach is not working.
Beans are instantiated classes that will have long running lives during the execution of your program, they are managed by Spring. This includes instances of classes that provides business logic or classes that provide program functionality, like database connections or a socket server.
Value Objects are short lived data object instances that is used by your application, which the student class seems to be. They are managed by your program code.
Upvotes: 2
Reputation: 5616
You dont find any tutorial for your problem because your usecase is not sutable for spring. In practice we dont use spring to achieve what you are trying to do. Spring is best suitable for dependency injection of classes with singleton behaviour for example service classes for which you will generally need single instance across your application.
Generally we use ORM like hibernate for the use case which you are ferering to.
Upvotes: 2