Spring best practices and guidelines
What are your best practices and guidelines with Spring? And why?
I want to start a discussion about Spring best practices and guidelines. A discussion where people can place their best practices and guidelines with an explanation why this best practice or guideline is good. Others can react on it with additional arguments why this is good, or with arguments why they disagree and maybe propose a better best practice or guideline.
My goal is: Get a list of all the Spring best practices and guidelines, including all their pro’s and con’s.
I'll start the discussion by giving some best practices and guidelines.
Always use auto-wiring. (Never ever use explicit wiring.)
Category: Spring core - configuration
Argumentation:
Bean id’s must be in lowerCamelCase.
Category: Spring core - configuration
Argumentation:
- All bean id’s in the Spring documentation and samples are in lowerCamelCase.
Don’t place all your beans in one xml file
Don’t place all your beans in one xml file (in large applications).
Split the configuration in different xml files. Minimal one xml file per architectural layer.
Category: Spring core – configuration
Argumentation:
- Long xml files are hard to read.
The default injection method to use is: setter injection
The default injection method to use is: setter injection.
Category: Spring core
Argumentation:
- Almost all the code in the Spring sample applications use setter injection.
Every bean must have an id
Every bean must have an id.
Always use id to specify the default name of the bean.
If you need characters in your bean name that are not allowed in the id attribute, then you can provide additional names with the name attribute.
But always give the bean an id. Because if, in the future, someone wants use the bean with a name following the XML IDREF constraints (and wants to use the id), then that's possible.
Category: Spring core – configuration
Argumentation:
- The id attribute can be validated by a xml parser, the name attribute can’t. And every good xml editor can validate on the id attribute. Because of the validation you will get less typo errors.
- To limit the risk of an accidental bean overwrite.
If no id or name attribute is specified, then Spring uses the bean’s class name as the name.
So if there are two beans of the same type without an id or name attribute specified, they will have the same name. (Note: this is an assumption, I still have to test this to be sure.)
In some situations one bean can overwrite the other if two beans have the same name.