开发者

Spring lookup method injection with parameters

Is there a way to use Spring lookup method inject with parameters? For example, I want to be able to instantiate prototype-scoped beans while passing them arbitrary parameters via construct开发者_StackOverflow中文版or.


It looks like this vital feature was finally added in Spring 4.1.0.RC2. I have tested it and it seems to work.

It was added as part of JIRA ticket SPR-7431 ("Passing lookup-method arguments to created bean constructor"):

<lookup-method/> should allow specifying any number of parameters. These parameters should be passed directly to the constructor of the newly created bean.

For more info on how the feature was finally added, this blog post was written by the guy who opened the JIRA ticket.


You can inject them via field/setter injection. (Note that constructor injection is frowned upon by spring, although it's supported)


in short, no. Spring does support something called "method injection" but it's different than you're thinking. Spring also supports constructor injection, but then you're not calling the constructor yourself, Spring is, and wiring it itself.

Instead, you can use reflection to instantiate the class and pass arbitrary parameters yourself:

Class<MyObject> clazz = MyObject.class; // this can be looked up or stored in a field, etc.
MyObject myObject = clazz.getConstructor(String.class, int.class)
                         .newInstance("arbitrary parameter", 42);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜