Search code examples
springspring-bean

Create runtime bean based on RESTful service values


Is there a way where I can create a runtime bean on spring. I needed this to happen since the values of the bean will be injected by the external entity through RESTful service. Is it possible for the runtime bean to still be autowired?


Solution

  • It is perfectly possible

    In your Controller (or in your Factory would be more elegant) you need to inject your Application context

    @Autowired
    private ApplicationContext applicationContext;
    

    You can create your beans like this:

    YourClassBean yourObject = this.applicationContext.getBean(YourClassBean.class, params);
    

    In your Spring configuration do this:

    @Bean
    @Scope(value = "prototype")
    YourClassBean yourClassBean(String params) {
        return new YourClassBean(params);
    }
    

    And your are done.

    In that example the Scope is Prototype which means that you will get a new object every time you call the method yourClassBean.

    Also in that example the params are a String (it is like the initialization parameters of your bean, but that is totally optional, and of course you might need or want more parameters in there and it is totally find)