Home > other >  Can we change @Component name runtime / dynamically
Can we change @Component name runtime / dynamically

Time:09-23

public abstract class Vehicle{
    private String vehicleName;
    
    public class Vehicle(String vehicleName){
        this.vehicleName = vehicleName;
    }

    public void drive();
}

@Component("Car")
public class Car implements vehicle(){
    
   public Car(String carName){
       super(carName);
   }

}

Here, My requirement is i want to set object name dynamically, i.e. as per above code, my reference to Car class is going to the name which i pass to @Component, and i want reference to Car class to be carName property from Car class.

Kindly suggest if it is possible or not.

Note - I dont want @Component name to be from any properties file, i want it from my existing car object.

CodePudding user response:

The "@Component" is a Spring concept to create a reusable and injectable component to another (and whatever) Spring Bean.

It should not be used for a POJO.

CodePudding user response:

@Component is to detect the custom beans, in your which is registering the component with Car as name, so as it is became a reference you are not allowed to change the Component name in runtime.

CodePudding user response:

According to your example, the short answer is 'NO'.

What you need to understand is @Component will creates a singleton bean, which will be initialized when the application context startup (unless you lazy initialize it). So you cannot really create a spring bean whenever you want.

Also note that these singleton beans should be stateless (only state they have is a shared state).

Since you haven't provide what is your real requirement, I suggest you to look at this bean scope documentation. It might be useful to you. Cheers!

  • Related