简体   繁体   中英

Get bean with specific Arguments to constructor in Spring

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); 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"/>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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