0

I was trying to pass the constructor parameter dynamically to a bean in the Springboot framework. I have followed this link using context.getBean(class, arg...) to pass the constructor parameters dynamically in Spring, but it did not successfully get the value and display the default values. What is wrong with my code?

Project Structure:

enter image description here

applicationContext.xml

    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="opBean" class="com.testout.service.Operation">
        <constructor-arg name="param1" value="default1" />
        <constructor-arg name="param2" value="default2" />
    </bean>

</beans>

Application

import com.testout.service.Operation;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


@SpringBootApplication
public class Application implements CommandLineRunner {
    public static void main(String[] args)  {
        SpringApplication.run(Application.class, args);
    }
    @Override
    public void run(String... args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        String param1 = "newValue1";
        String param2 = "newValue2";
        Operation op = (Operation) context.getBean("opBean", param1, param2);
        op.printParams();
    }
}

Operation

package com.testout.service;

public class Operation {
    private String param1;
    private String param2;

    public Operation(String param1, String param2){

        this.param1 = param1;
        this.param2 = param2;
        System.out.println("param1: " + param1 + ", param2: " + param2);
    }
    public void printParams(){

        System.out.println(this.param1);
        System.out.println(this.param2);
    }
}

output:

2021-02-19 16:45:58.201  INFO 43664 --- [           main] com.testout.controller.Application       : No active profile set, falling back to default profiles: default
2021-02-19 16:45:59.097  INFO 43664 --- [           main] com.testout.controller.Application       : Started Application in 1.494 seconds (JVM running for 2.074)
param1: default1, param2: default2
default1
default2
Chee Conroy
  • 163
  • 3
  • 11

1 Answers1

1

if you want this behavior you have to set the scope of your bean to prototype

<bean id="opBean" class="com.testout.service.Operation" scope="prototype"/> 
badger
  • 2,908
  • 1
  • 13
  • 32