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

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();
     }
    }
cotinue 回答:如何将参数从getBean传递给使用@Bean批注创建的bean?

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

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

}
本文链接:https://www.f2er.com/3065784.html

大家都在问