Twelve best practices for spring xml configuration

Source: Internet
Author: User

Spring is a powerful Java application framework. It is widely used in Java applications and provides enterprise-level services for plain old Java objects (pojo. Spring uses the dependency injection mechanism to simplify work and improve testability. The configuration file (usually in XML format) specifies spring bean, dependencies, and services required by bean. However, these xml configuration files are lengthy and not practical. It is difficult to read and manage large projects that need to define a large number of spring beans.
In this article, I will show you 12 best practices for spring xml configuration. Some of these practices are more necessary than best practices. Note that other factors (such as setting the domain model) may also affect the xml configuration, but this article focuses on the readability and manageability of xml configuration.

1. Avoid using the autowiring Function
Spring can automatically bind dependencies through Bean class introspection, so you do not need to explicitly specify bean attributes and constructors. Bean attributes can be automatically bound by property names or type matching. The constructor performs automatic binding through type matching. You can even specify the autowiring mode, which can guide spring to select an appropriate running mechanism. Let's take a look at the following example:
<Bean id = "orderservice"
Class = "com. lizjason. Spring. orderservice"
Autowire = "byname"/>
The attribute name of the orderservice class is used in the container to match the bean instance. Automatic Binding may save some typing workload and reduce confusion. However, this method should not be used in real projects because it sacrifices the readability and maintainability of configurations. Many guides and introductions boast that automatic binding is an excellent feature of spring, without mentioning the sacrifice of this feature. In my opinion, this is like the object-pooling in spring. to a greater extent, it is just a publicity gimmick. It is a good method for streamlining xml configuration files, but it actually increases complexity, especially when running projects that contain a large number of class declarations. Although spring allows both automatic binding and explicit binding, xml configuration is even more obscure.

2. Use naming conventions
This principle also applies to Java encoding. Using clear, descriptive, and consistent naming conventions in a project helps developers understand XML configurations. For example, the bean ID can be named according to the Java field name conventions. The bean ID of the orderservicedao instance should be named orderservicedao. For large projects, you can add the package name as the prefix before the bean ID.

3. Simple Form
The conciseness avoids the lengthy format because it moves the attribute value and reference from the child element into the attribute. For example:
<Bean id = "orderservice"
Class = "com. lizjason. Spring. orderservice">
<Property name = "companyName">
<Value> lizjason </value>
</Property>
<Constructor-Arg>
<Ref bean = "orderdao">
</Constructor-Arg>
</Bean>
You can rewrite the above Code in a concise form as follows:
<Bean id = "orderservice"
Class = "com. lizjason. Spring. orderservice">
<Property name = "companyName"
Value = "lizjason"/>
<Constructor-Arg ref = "orderdao"/>
</Bean>

The concise form can be used since version 1.2. Note that there is no concise form for <ref local = "...">.
The concise form not only saves the typing workload, but also makes the xml configuration file clearer. When a configuration file defines a large number of classes, it can significantly improve readability.

4. For constructor parameter matching, the type is better than the subscript
When the constructor contains more than one parameter of the same type or the tag of the attribute value is occupied, spring allows subscript starting from 0 to avoid confusion. For example:
<Bean id = "billingservice"
Class = "com. lizjason. Spring. billingservice">
<Constructor-Arg Index = "0" value = "lizjason"/>
<Constructor-Arg Index = "1" value = "100"/>
</Bean>
It is better to use the type attribute, as shown below:
<Bean id = "billingservice"
Class = "com. lizjason. Spring. billingservice">
<Constructor-Arg type = "Java. Lang. String"
Value = "lizjason"/>
<Constructor-Arg type = "int" value = "100" type = "codeph" text = "codeph"/>
</Bean>

Using index can reduce some code, but it is more error-prone and difficult to read than the type attribute. Index should be used only when the constructor parameters are not clear.

5. Try to reuse the defined Bean
Spring provides a mechanism similar to inheritance to reduce the replication of configuration information and simplify xml configuration. Define a subclass to inherit the configuration information from the parent class, and the parent class actually becomes a template of the subclass. This is the so-called reuse of large projects. You only need to set abstract = true in the parent bean and specify the parent reference in the Child bean. For example:
<Bean id = "abstractservice" abstract = "true"
Class = "com. lizjason. Spring. abstractservice">
<Property name = "companyName"
Value = "lizjason"/>
</Bean>

<Bean id = "shippingservice"
Parent = "abstractservice"
Class = "com. lizjason. Spring. shippingservice">
<Property name = "shippedby" value = "lizjason"/>
</Bean>

The shippingservice class inherits the value of the companyName attribute from the abstractservice class-lizjason. If a bean does not specify a class or factory method, the bean is abstract.

6. During import, the bean definition is compiled by applicationcontext.
Like the import in the ant script, the import element of spring is very useful for compiling modular bean definitions. For example:
<Beans>
<Import resource = "billingservices. xml"/>
<Import resource = "shippingservices. xml"/>
<Bean id = "orderservice"
Class = "com. lizjason. Spring. orderservice"/>
<Beans>

However, compared to using import for preassembly in xml configuration, configuring these beans through applicationcontext is more flexible. Using applicationcontext makes xml configuration easier to manage. You can pass a set of bean definitions to the applictioncontext constructor as follows:
String [] serviceresources =
{"Orderservices. xml ",
"Billingservices. xml ",
"Shippingservices. xml "};
Applicationcontext orderservicecontext = new
Classpathxmlapplicationcontext (serviceresources );

7. Use Id as the bean identifier
You can specify an ID or name as the bean identifier. Although using ID cannot improve readability, it can use XML analysis programs to verify bean reference. If you cannot use an id due to the XML idref constraint, you can use the name as the bean identifier. The constraint of XML idref is that the ID must start with a letter (or a punctuation mark defined in the XML specification), followed by letters, numbers, hyphens, underscores, colons, or periods. In fact, XML idref constraints are rarely encountered.

8. Use dependency-check during development)
You can set a non-default value for the dependency-check attribute in bean definition, such as simple, objects, or all, so that the container can perform dependency check. Dependency check is useful when you need to explicitly or automatically bind all attributes (or certain attributes) of the bean.
<Bean id = "orderservice"
Class = "com. lizjason. Spring. orderservice"
Dependency-check = "objects">
<Property name = "companyName"
Value = "lizjason"/>
<Constructor-Arg ref = "orderdao"/>
</Bean>

In this example, the container ensures that the attribute set for orderservice bean is not primitives or collections. You can also set the default dependency check for all beans, but we seldom do this, because some bean attributes do not need to be set at all.

9. Add the first comment for each configuration file
It is best to replace the built-in annotations in the XML configuration file with descriptive IDs and names. In addition, it is useful to add a configuration file header, which can be used to outline the bean defined in the file. You can add the description to the description label. For example:
<Beans>
<Description>
This file defines Billing Service
Related beans and it depends on
Baseservices. XML, which provides
Service bean templates...
</Description>
...
</Beans>
One advantage of using the description tag is that you can easily use the tool to select a description from the tag.

10. For changes, the team members should actively communicate with each other
When refactoring Java code, you must update the configuration file at any time and notify team members. Xml configuration files are also code, and they are vital parts of the application, but they are difficult to read and maintain. In most cases, you need to read both the xml configuration file and the running Java code.

11. setter injection is better than constructor Injection
Spring provides three types of dependency injection: constructor injection, setter injection, and method injection ). We generally only use the first two methods.
<Bean id = "orderservice"
Class = "com. lizjason. Spring. orderservice">
<Constructor-Arg ref = "orderdao"/>
</Bean>

<Bean id = "billingservice"
Class = "com. lizjason. Spring. billingservice">
<Property name = "billingdao"
Ref = "billingdao">
</Bean>

In this example, the orderservice class uses constructor injection, while the billingservice class uses setter injection. Constructor injection ensures that beans are not created in an invalid state, but setter injection is more flexible and easier to manage, especially when the class contains many attributes and is optional.

12. Do not abuse dependency Injection
Last, spring applicationcontext can create Java objects for you, but not all Java objects should be created through dependency injection. For example, a global object cannot be created using applicationcontext. Spring is a great framework. However, for readability and manageability, if a large number of beans are defined, XML-based configuration may become a problem. Over-using dependency injection makes xml configuration complicated and bloated. You must know that with powerful IDE (such as Eclipse and intellij), Java code is easier to read, maintain, and manage than XML files.

Conclusion
XML is a common spring configuration method. However, if a large number of beans are defined, the XML-based configuration will become lengthy and not practical. Spring provides a wide range of configuration options to make the xml configuration clearer by making appropriate use of the options. However, some options (such as autowiring) tend to reduce the readability and maintainability of the configuration file. Following the best practices described in this article will help you create clear and easy-to-read xml configuration files.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.