简体   繁体   中英

Java: Spring : How to pass params to the constructor dynamically?

Pretend that I have a class:

public class Person {

 private final String first;
 private final String last;
 private final Address address;

 public Person(String first, String last, Address address){
  this.first = first;
  this.last = last;
  this.address = address;
 }

 public String getFirst() {
  return first;
 }

 public String getLast() {
  return last;
 }

 public Address getAddress() {
  return address;
 }
}

And I have a proxy class for the above as :

public class PersonProxy
{
    private Person person;

    // --Other properties---

    public PersonProxy( Person person)
    {
        this.person = person;
    }
}

We used to create an instance of the PersonProxy this way:

PersonProxy proxy = new PersonProxy(new Person("Betty", "Kale" , "some address"));

But we are moving to Spring recently and would like to declare these 2 classes as beans in the context file but want to pass those params, in the constructor of the Person class, dynamically when creating an object of the proxy. How can declare that kind of bean for those 2 classes in the context file and how can I create the instance of the PersonProxy class using those beans to replace:

PersonProxy proxy = new PersonProxy(new Person("Betty", "Kale" , "some address"));

Thanks is advance.

One way you can do that is using a FactoryBean , eg creating a PersonProxyFactoryBean . See this blog post for more details on FactoryBeans.

Create Person as : Person person = context.getBean( Person.class,"Betty", "Kale" , "some address");

And then create the PersonProxy as : PersonProxy proxy= context.getBean(PersonProxy.class, person );

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