DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • What Is Istio Service Mesh?
  • How Web3 Is Driving Social and Financial Empowerment
  • Building A Log Analytics Solution 10 Times More Cost-Effective Than Elasticsearch
  • Send Email Using Spring Boot (SMTP Integration)

Trending

  • What Is Istio Service Mesh?
  • How Web3 Is Driving Social and Financial Empowerment
  • Building A Log Analytics Solution 10 Times More Cost-Effective Than Elasticsearch
  • Send Email Using Spring Boot (SMTP Integration)
  1. DZone
  2. Coding
  3. Frameworks
  4. Instanciating Spring component with non-default constructor from another component

Instanciating Spring component with non-default constructor from another component

Lubos Krnac user avatar by
Lubos Krnac
·
May. 30, 13 · Interview
Like (1)
Save
Tweet
Share
50.96K Views

Join the DZone community and get the full member experience.

Join For 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

Spring Framework

Opinions expressed by DZone contributors are their own.

Trending

  • What Is Istio Service Mesh?
  • How Web3 Is Driving Social and Financial Empowerment
  • Building A Log Analytics Solution 10 Times More Cost-Effective Than Elasticsearch
  • Send Email Using Spring Boot (SMTP Integration)

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: