Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor that takes arguments - Define as ordinary object or spring bean?

Tags:

spring

Let's say that I have a class with a constructor that takes one or more arguments. Let's also say that the arguments are expected to be som kind of input from the user. I.e the argument can not be known at compile-time or config-time, only at runtime. Should I define my class as a prototype spring bean or should I just create it with "new".

If I should define it as a bean, how can I pass in the arguments?

like image 777
Ludwig Magnusson Avatar asked May 15 '12 19:05

Ludwig Magnusson


2 Answers

This is problematic in Spring. If your class has no dependencies on other beans, just create it with new. If you have a class depending on other Spring beans but still you want pass some runtime arguments, currently Spring does not support it.

However have a look at SPR-7431 and my article about passing custom argument to <lookup-methods/>. If all goes well, this feature should be part of Spring 3.2 and it should match your requirements. It basically allows creating prototype-scoped beans while still passing some constructor argument.

like image 189
Tomasz Nurkiewicz Avatar answered Nov 05 '22 00:11

Tomasz Nurkiewicz


Unless your class also has dependencies on other beans in your context, then no, you shouldn't make it a bean - there's no point. Just use new.

The only compelling reason to make it a bean is if it does depend on other beans, in which case a prototype-scoped bean is justified. However, if the class requires those runtime values in its constructor, then you can't really do that, short of changing the class to inject them via some method instead of using the constructor.

like image 5
skaffman Avatar answered Nov 05 '22 00:11

skaffman