如何将参数从getBean传递给使用@Bean批注创建的bean?

时间:2019-11-20 12:49:07

标签: java spring annotations javabeans

Spring有一个getBean重载,它接受参数。 如何将这些参数传递给Bean的@Bean创建函数?

class Person
{
    String name;
    Person(String name) {
        this.name = name;
    }
}

    public class SpringAnnotationMain {
     public static void main(String[] args) {
         AnnotationConfigApplicationContext ctx =    new AnnotationConfigApplicationContext(SpringAnnotationMain.class); 
           Person x = ctx.getBean(Person.class, new Object[] {"Alice"}); 
           System.out.println(x.name);

         ctx.close();
     }
    }

1 个答案:

答案 0 :(得分:0)

Spring会将参数作为参数传递给@Bean函数,然后从那里传递给bean的构造函数,

@Configuration
class MyConfig {
     @Bean
     @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
     Person createPerson(String name)
     {
         return new Person(name);
     }

}