evermean
evermean

Reputation: 1307

Spring runtime object/bean creation

I am working on a project which uses the spring-framework (v3.2.1) but since I'm new to the spring way of doing things, I'm currently stuck with the following problem....it would be great if someone could point me into the right direction:

I am trying to create instances of a Job class at runtime. The Job class itself uses some services which are @Autowired in the Job class. Since the autowiring does only work for objects which are under the control of the spring container ... the first thing that came to my mind was the following:

@Component
@Scope("prototype")
class Job{

  @Autowired
  MyService service

  String name
  String group
  .
  .
  .

  public Job(){

  }

  public Job(String name, String group){

    this.name = name;
    this.group = group;

  }

  public void start(){

    //some code, use of service etc.
  }

}

Now I can use the application context to get a new Job by calling context.getBean("job"). The new job instance is created by invoking the default constructor and therefore I have to set the name and group parameter after I obtained a new Job instance:

Job j = context.getBean("job");

j.setName("Test");
j.setGroup("someGroup");
j.start()

I am currently trying to figure out if there is some way of specifying the parameters with which the instance of a job is going to be created at runtime. So that I can instantiate new objects of the job class with a different state.

As I mentioned above I am currently stuck here and do to my lack of experience with spring I'm having a hard time figuring out the best way to accomplish this. Perhaps there is some universally accepted way or pattern to do such things. It would be great if someone with more spring experience could point me into the right direction.

Thanks a lot!

Upvotes: 3

Views: 2170

Answers (2)

Tom
Tom

Reputation: 43

BeanFactory getBean(String name, Object[] args)

You can use this to pass an array of arguments

Upvotes: 1

Related Questions