Tuomas Toivonen Tuomas Toivonen - 1 year ago 84
Java Question

Is it possible to autowire method arguments at runtime in Spring

Is it possible to inject new instances of prototype scoped beans to Controller's method arguments at runtime using annotations in Spring? So whenever the method is called, Spring would inject the qualifying bean as its argument, familiarly as it injects @ModelAttribute. As far as I know, @Autowired fields are injected only once when context is created. Obtaining the bean from context's factory method isn't an option, as that would expose framework to its component, thus violating the hollywood principle.

I have almost completed reading Spring in Action book and have been reading Spring Reference a lot, but haven't found any info regarding this question.

Answer Source

You have a couple of options.

Define a prototype bean and inject that wrapped in an ObjectFactory

private ObjectFactory<PrototypeBean> factory;

You can then retrieve it in your handler method. For example

public String handlerMethod() {
    PrototypeBean instance = factory.getObject();
    return "view";

Every time you call factory.getObject(), you'll get a new instance.

As for doing this directly, no, Spring MVC does not have a built-in feature for having beans injected while invoking handler methods, with @Autowired or otherwise.

However, the HandlerMethodArgumentResolver API allows you to define an implementation for any type of parameter you want. You can define a new annotation and use it to annotate the appropriate handler method parameter(s). The implementation would look for the annotation and resolve an instance from an injected ApplicationContext. You could do this by name, by type, however you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download