1
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.

  • 1
    No you cannot. Also what would be the purpose? Also why is `Car` even a component... – M. Deinum Sep 23 '21 at 10:01
  • You cannot change the component name at runtime. You could use FactoryBeans, but I'm not sure what you want to accomplish with your code, so let me ask: can you please add some details? What's the matter you want to address, in this case? – Gregorio Palamà Sep 23 '21 at 10:27
  • 1
    What is exactly your use case? – João Dias Sep 23 '21 at 10:32
  • You can dynamically add a bean to Spring with a name that you choose. See https://stackoverflow.com/questions/4540713/add-bean-programmatically-to-spring-web-app-context – Mustafa Sep 23 '21 at 12:40

3 Answers3

1

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!

ray
  • 1,512
  • 4
  • 11
0

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.

J. DEMARE
  • 28
  • 7
  • i think he is just learning with some tutorial, seems he is not considering the class as a pojo. – saif Sep 23 '21 at 13:03
0

@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.

saif
  • 1,182
  • 14
  • 27