Robert Munteanu
Robert Munteanu

Reputation: 68268

Making sure a Spring Bean is properly initialised

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.

Upvotes: 10

Views: 3403

Answers (4)

Paul McKenzie
Paul McKenzie

Reputation: 20096

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

Upvotes: 2

kgiannakakis
kgiannakakis

Reputation: 104178

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%

Upvotes: 8

Adamski
Adamski

Reputation: 54695

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.

Upvotes: 5

skaffman
skaffman

Reputation: 403471

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.

Upvotes: 6

Related Questions