Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Instanciating Spring component with non-default constructor from another component

DZone's Guide to

Instanciating Spring component with non-default constructor from another component

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

I'd like to show how to instantiate Spring's component with non-default constructor (constructor with parameters) from other Spring driven component because it seems to me that a lot of Java developers doesn't know that this is possible in Spring. 

First of all, simple annotation based Spring configuration. It's it is scanning target package for components.

@Configuration
@ComponentScan("sk.lkrnac.blog.componentwithparams")
public class SpringContext {
}

Here is component with non-default constructor. This component needs to be specified as prototype, because we will be creating new instances of it. It also needs to be named (will clarify why below).

@Component(SpringConstants.COMPONENT_WITH_PARAMS)
@Scope("prototype")
public class ComponentWithParams {
 private String param1;
 private int param2;
 
 public ComponentWithParams(String param1, int param2) {
  this.param1 = param1;
  this.param2 = param2;
 }

 @Override
 public String toString() {
  return "ComponentWithParams [param1=" + param1 + ", param2=" + param2
    + "]";
 }
}

Next component instantiates ComponentWithParams. It needs to be aware of Spring's context instance to be able to pass arguments into non-default constructor. getBean(String name, Object... args) method is used for that purpose. First parameter of this method is name of the instantiating component (that is why component needed to be named). Constructor parameters follow.

@Component
public class CreatorComponent implements ApplicationContextAware{
 ApplicationContext context;
 
 public void createComponentWithParam(String param1, int param2){
  ComponentWithParams component = (ComponentWithParams)
    context.getBean(SpringConstants.COMPONENT_WITH_PARAMS, 
      param1, param2);
  System.out.println(component.toString() + " instanciated...");
 }

 @Override
 public void setApplicationContext(ApplicationContext context)
   throws BeansException {
  this.context = context;
 }
}

Last code snippet is main class which loads Spring context and runs test.

public class Main {

 public static void main(String[] args) {
  AnnotationConfigApplicationContext context = 
    new AnnotationConfigApplicationContext(SpringContext.class);
  CreatorComponent invoker = context.getBean(CreatorComponent.class);
  
  invoker.createComponentWithParam("Fisrt", 1);
  invoker.createComponentWithParam("Second", 2);
  invoker.createComponentWithParam("Third", 3);
  context.close();
 }
}

Console output:

ComponentWithParams  instanciated...
ComponentWithParams  instanciated...
ComponentWithParams  instanciated...

And that's it. You can download souce code on Github

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}