Spring:如何在运行时将值传递给嵌套的Bean构造函数

时间:2015-09-18 07:47:09

标签: java spring

考虑这两个类。

@Component
public class Foo {
    private String name;

    public Foo(@Value("name") String name) {
        this.name = name;
    }
}

@Component
public class Bar {
    private Foo foo;

    public Bar(@Value("#{bar}") Foo foo) {
        this.foo = foo
    }
}

如何在将Foo传递给Bar之前更改Foo中的name值?

没有Spring,我们可以做到这一点

Foo foo = new Foo("newName");
Bar bar = new bar(foo);
// do something with bar

但是我如何在运行时使用Spring执行此操作?

运行时将类似于

public static void main(String[] args) {
    String name = "newValue"; // get from user or read from a file
    ApplicationContext context = new ClassPathXmlApplicationContext("foo.xml");
    // do some magic here
    Bar bar = context.getBean("bar", Bar.class);
    assert bar.getFoo().getName().equals(name);
}

0 个答案:

没有答案