Java – what is the best way to initialize beans?
In spring, you can make ApplicationContext XML calls the constructor to initialize a bean, or you can set properties on the bean What is the trade-off between the two methods? Building a constructor (enforcing all required contracts in a method) is the best way, or better, having all properties (so that injection can be selectively performed, such as in unit testing)
What is a trade-off between writing a bean that uses a constructor to establish its initial state, or using properties, or possibly the afterproperties () method?
Solution
I didn't know there was a "best" way to initialize a bean I think everyone has advantages and disadvantages. According to the situation, one or another may be appropriate This is certainly not an exhaustive list, but here are some things to consider
Using constructors allows you to have an immutable bean Non deformable objects will be good if they can adapt to your design They do not require replication, serialization, access, or other special processing between threads If you have a setter, your object is not immutable Using constructors also ensures that objects are properly initialized After the constructor is completed, the object is valid If your object needs a setter to initialize it, there may be an invalid object
On the other hand, using constructors often leads to scaling problems Typically, you will need many different constructors, most of which will be a superset of another constructor Usually these are for convenience For example:
public class Person { public Person(String name) { ... } public Person(String name,String phone) { ... } public Person(String name,String phone,String email) { ... } }
Another alternative I like very much is the so-called "enhanced" builder pattern proposed by Jos o Bloch on JavaOne You can see this in his book effective Java, Second Edition If you look at how patterns are used, it will also solve your "afterproperties" method problem The builder pattern ensures that objects are initialized correctly
This is an additional blog post discussion mode: http://www.screaming-penguin.com/node/7598
I don't know if it meets your spring requirements, but generally speaking, I'm a fan of architects