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();
}
}
答案 0 :(得分:0)
Spring会将参数作为参数传递给@Bean函数,然后从那里传递给bean的构造函数,
@Configuration
class MyConfig {
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
Person createPerson(String name)
{
return new Person(name);
}
}