How to pass parameters dynamically to Spring beans

后端 未结 5 2153
盖世英雄少女心
盖世英雄少女心 2020-12-28 14:31

I am new to Spring.

This is the code for bean registration:

 


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-28 15:14

    If i get you right, then the correct answer is to use #getBean(String beanName, Object... args) which will pass arguments to bean. I can show you, how it is done for java-based configuration, but you'll have to find how it is done for xml based configuration.

    @Configuration
    public class ApplicationConfiguration {
    
      @Bean
      @Scope("prototype") //As we want to create several beans with different args, right?
      String hello(String name) {
        return "Hello, " + name;
      }
    }
    
    //and later in your application
    
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
    String helloCat = (String) context.getBean("hello", "Cat");
    String helloDog = (String) context.getBean("hello", "Dog");
    

    Is this what are you looking for?

    Upd. This answer gets too much upvotes and nobody looks at my comment. Even though it's a solution to problem, it is considered as spring anti-pattern and you shouldn't use it! There are several different ways to do things right using factory, lookup-method, etc..

    Please use the following SO post as a point of reference: create beans at runtime

提交回复
热议问题