2

assume I have that class

public Student{
 private String name;
 private Address address;

 public Student(String fName, Address address){
  name = fname;
  this.address = address;
}

I defined this class within Spring configuration as

 <bean name="studentInstance" class="StackOverFlow.Student"/>

now i'd like to use getBean with parameter I will pass to constructor. equal to Student s = new Student(name,address) I know Spring supplies a methond getBean(class_name,parms....) however I dont know how I should config Spring.xml configuration file. I would like to avoid using Setter and getter in order to fill a new bean.

I found lots of example of how to define </constructor-arg> within the xml but each time it was with default values. here I let the user to enter different values for each object. I'd like to use ApplicationContext context = new ClassPathXmlApplicationContext(Spring.xml file path); Student s= (Student)context.getBean("studentInstance",name,address);

I need help with the configuration file only

Thanks in Advance!!

I already checked those links : Link1 Link2 Link3 Link4

~~~~~Edit ~~~~~~~

Solved! constructor-injection is not needed here I just added prototype scope to my bean as shown below.

<bean name="carInstance" class="MainApp.bl.GasStation.Car" scope="prototype"/>
Community
  • 1
  • 1
tamir_sagi
  • 155
  • 1
  • 10
  • 1
    Side note, Spring creates Singleton of a bean by default. If you need more instances, first you will have to declare your bean as a prototype. – John Jul 02 '15 at 09:17
  • Wow!! I just added scope="prototype" to my bean and everything worked like magic!!! why it is not mentioned or shown anywhere! tnx brother! – tamir_sagi Jul 02 '15 at 09:55
  • If this helped you, you may accept the answer by clicking gray check mark :) – John Jul 02 '15 at 10:20

1 Answers1

1

Firstly, such bean must obviously be declared as prototype.

The Prototype scopes a single bean definition to have any number of object instances. If scope is set to prototype, the Spring IoC container creates new bean instance of the object every time a request for that specific bean is made <

Object getBean(String name, Object... args)throws BeansException

Return an instance, which may be shared or independent, of the specified bean. Allows for specifying explicit constructor arguments / factory method arguments, overriding the specified default arguments (if any) in the bean definition.

Refer to following question for configuration:

Spring <constructor-arg> element must specify a ref or value

Note, you will have to wrap primitives into their Wrapper objects to avoid having predefined values when object is created.

Community
  • 1
  • 1
John
  • 5,189
  • 2
  • 38
  • 62