tags:

views:

247

answers:

4

What is the most concise way of making sure that a Spring bean has all properties set and the init method called?

I'll favour answers which use setter injection and XML configuration, since that's what I'm using right now.


I'm trying to evade the case where I either forget to configure a setter or call the init-method.


In future projects I would favour skaffman's response, but I've chosen the one which suits me right now.

+5  A: 

Use the @Required annotation on the setter methods. Spring will then check that they've all been set without you having to check manually.

Alternatively, annotate your init methods with @PostConstruct, and Spring will invoke them for you.

skaffman
Wouldn't spring set all the dependencies before giving you a bean?
fastcodejava
+4  A: 

You can add the dependency-check attribute to your bean definition to ensure that all objects / primitives / both have been set.

<bean id="myBean" class="com.foo.MyBean" dependency-check="objects"/>

Skaffman's answer gives more control, but does introduce a compile-time dependency on Spring which you may / may not want.

Adamski
Is "objects" some magic value?
skaffman
"objects" means that Spring will check that only properties for objects (not primitives) have been set.
Adamski
Hmm, I didn't know you could do that, that looks like hard-core Spring 1.2 stuff :)
skaffman
This method also requires you to remember to add the dependency-check attribute to each bean definition, so it's still prone to forgetfulness.
skaffman
@Adamski: There's also default-dependency-check and default-init-method/default-destroy-method. You might want to include those in your answer.
Robert Munteanu
+5  A: 

This poll is exactly what you are looking for.

Here are the results:

  • By using the dependency-check attribute in XML: 11.52%
  • By using the @Required annotation (or a custom annotation): 21.40%
  • By using InitializingBean and an assert facility: 23.87%
  • By using init-method and an assert facility: 14.40%
  • I don't have to, because I use constructor injection for required properties: 19.34%
  • I check my dependencies in my business methods: 7.41%
  • I don't check required dependencies: 34.16%
kgiannakakis
+1: Interesting ... although surprised that the top vote is "I don't check required dependencies".
Adamski
I don't check either - but I want to. This is why I asked the question.
Robert Munteanu
That's a pretty old poll, also, so Spring developers will be more aware of the likes of @Required now.
skaffman
+2  A: 

Use the following attributes of the beans tag to make sure dependency checking and the init method is called on all beans, but it rather assumes you don't call your method "innit".

<beans default-init-method="init" default-dependency-check="objects">

see link

Paul McKenzie