0

So my problem is, I have a bean which I would like to inject dynamically based on runtime values. Lets say I have class A which has private variable B. I would like to inject my variable B (upon creation of the bean) via spring with value I got from user (for example). How can I do that ? Should I just use getBean() and then use setter method for my variable or is there any better way ?

EDIT:

@Bean 
class A {
    private int B;
    ... 
}    

main {
    context = someContext("myConfigFileWhereBeansAreDefined");
    int value = getIntFromUser();

    // I want to have myNewBean injected with "value" i got from user
    A myNewBean = context.getBean("A");
}
Druudik
  • 955
  • 1
  • 10
  • 32
  • Can you please add some code snippets which explains what you are trying to do? – Matthias Steinbauer Nov 16 '17 at 15:15
  • can your beans which you want to inject at runtime be of same type? I mean does all those beans implement same interface ? – pvpkiran Nov 16 '17 at 15:24
  • @MatthiasSteinbauer I added some Code – Druudik Nov 16 '17 at 15:25
  • @pvpkiran Yes they are instances of the same class. – Druudik Nov 16 '17 at 15:26
  • see my answer here. I think it is pretty much the same problem https://stackoverflow.com/questions/44000672/spring-how-to-change-interface-implementations-at-runtime/44001051#44001051 – pvpkiran Nov 16 '17 at 15:28
  • Possible duplicate of [Spring: how to change interface implementations at runtime](https://stackoverflow.com/questions/44000672/spring-how-to-change-interface-implementations-at-runtime) – pvpkiran Nov 16 '17 at 16:04
  • You're pretty much where you need to be. It's a variation of the Command or Strategy patterns (depends on who you ask) – kolossus Nov 16 '17 at 21:15
  • you can put the user desired value in a .property file and read it via the @ Value annotation, and then you can autowire the whole bean A @Bean class A{ @Value("${user.input.value}") private int B; } – Amr Alaa Nov 16 '17 at 23:51

0 Answers0