Reputation: 68268
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
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
Reputation: 104178
This poll is exactly what you are looking for.
Here are the results:
Upvotes: 8
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
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