Home > Back-end >  How to create a bean and autowire at run time dynamically based on user input param
How to create a bean and autowire at run time dynamically based on user input param

Time:10-23

How to create Student class object at run time dynamically based on the param received in the URL and inject in to WebapplicationContext so the IoC container can auto wire it automaticallly to Access class ?

Need to create a bean at run time based on user parameters

@RestController
public class FunRestController {
    
    @GetMapping("/{id}/{name}")
    public String welcomeToBoot(@PathVariable int id, @PathVariable String name) {
                 // How to create Student class object at run time dynamically based 
                 // on the param received in the URL and can auto wire it dynamically to ***Access*** class below ?
        return "Welcome "   name;
    }
}

Need to Autowire a run time bean created

public class Access {
    @Autowired
    Student s;
    void print() {
        System.out.println(s.name);
    }
}

POJO :

public class Student {
    public int id;
    public String name;
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

CodePudding user response:

I would suggest not to @Autowired the Student object but instead, pass it as a parameter to a function. Something as follows:

public class Access {
    void print(Student s) {
        System.out.println(s.name);
    }
}

Now you just need to call print() method with the given Student. If you need Access to be a Spring-managed Bean so that you can inject it into your Controller, you would need to annotate it with @Component.

CodePudding user response:

Instead of creating bean, you can create a thread local variable and initialise it as the first thing. Then it'll be available throughout the request / response scope

  • Related