如果我有这样的豆:
@Lazy
public class MyBean{
public MyBean(String argument){}
@Bean
@Scope("prototype")
public MyBean myBean(String argument){
return new MyBean(argument);
}
}
有没有办法通过Provider获取该bean的实例,如下所示:
@Component
public class MyOtherBean{
@Autowired
private javax.inject.Provider<MyBean> myBean;
public void operation(){
MyBean bean = myBean.get(); //I would like to pass argument in when getting the bean
}
}
我也在阅读@Lookup注释,因为它有类似(或相同的)效果,但是我使用的是Spring 3.1.1,这个注释没有实现但是我相信... 如果我在这里尝试做的事情不能这样做,你将如何进行这样的功能呢? 谢谢你的帮助:)
答案 0 :(得分:1)
ApplicationContext
为您提供此功能。
public class Test {
public static void main(String args[]) throws Exception {
ApplicationContext ctx = new AnnotationConfigApplicationContext(Factory.class);
// calls the @Bean factory method for the myBean bean with the argument provided
ctx.getBean("myBean", "first");
ctx.getBean("myBean", "second");
}
}
@Configuration
class Factory {
@Bean()
@Scope("prototype")
public MyBean myBean(String arg) {
return new MyBean(arg);
}
}
class MyBean {
public MyBean(String arg) {
System.out.println(arg);
}
}