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

问题描述 投票:0回答:1

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();
     }
    }
java spring annotations javabeans
1个回答
0
投票

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

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

}
© www.soinside.com 2019 - 2024. All rights reserved.