如何动态地将参数传递给Spring bean

Ram*_*h J 20 java spring javabeans

我是Spring的新手.

这是bean注册的代码:

<bean id="user" class="User_Imple"> </bean>
<bean id="userdeff" class="User"> </bean>
Run Code Online (Sandbox Code Playgroud)

这是我的bean类:

public class User_Imple implements Master_interface {

    private int id;
    private User user; // here user is another class

    public User_Imple() {
        super();
    }

    public User_Imple(int id, User user) {
        super();
        this.id = id;
        this.user = user;
    }

    // some extra functions here....
}
Run Code Online (Sandbox Code Playgroud)

这是我执行操作的主要方法:

public static void main(String arg[]) {

    ApplicationContext context = new ClassPathXmlApplicationContext("/bean.xml");
    Master_interface master = (Master_interface)context.getBean("user");

    // here is my some operations..
    int id = ...
    User user = ...

    // here is where i want to get a Spring bean
    User_Imple userImpl; //want Spring-managed bean created with above params
}
Run Code Online (Sandbox Code Playgroud)

现在我想用参数调用这个构造函数,这些参数是在我的main方法中动态生成的.这就是我想要动态传递的意思 - 不是静态的,就像在我的bean.config文件中声明的那样.

Vad*_*huk 27

如果我说得对,那么正确的答案是使用#getBean(String beanName,Object ... args)将参数传递给bean.我可以告诉你,它是如何为基于java的配置完成的,但你必须找到它是如何为基于xml的配置完成的.

@Configuration
public class ApplicationConfiguration {

  @Bean
  @Scope("prototype") //As we want to create several beans with different args, right?
  String hello(String name) {
    return "Hello, " + name;
  }
}

//and later in your application

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
String helloCat = (String) context.getBean("hello", "Cat");
String helloDog = (String) context.getBean("hello", "Dog");
Run Code Online (Sandbox Code Playgroud)

这是你在寻找什么?

UPD.这个答案得到了太多的赞成,没有人看我的评论.虽然它是问题的解决方案,但它被认为是弹簧反模式,你不应该使用它!有几种不同的方法可以使用工厂,查找方法等来做正确的事情.

请使用以下SO帖子作为参考:在运行时创建bean

  • 请注意,使用"DI"时这不是最佳解决方案,因为实际上我们有一个"服务定位器"(与DI相反).通常,当您遇到太多context.getBean时,它意味着某些事情以错误的方式完成. (4认同)

Chr*_*ris 5

请看一下构造函数注入

此外,看一看IntializingBean的BeanPostProcessor的一个springbean的其他生命周期拦截。

  • 能否请您引用为什么`setter`注入优先于构造方法的引用 (2认同)