Spring XML configuration 12 best Practices

Source: Internet
Author: User
Tags abstract constructor header readable resource xml parser
XML in this article, for the configuration of spring XML, I'll show you 12 of better practices. Some of these practices are not only good practice, but also necessary practice. In addition, other factors, such as the design of domain models, can affect the configuration of XML, but this article focuses on the readability and manageability of XML configurations.

  1. Do not use autowiring

Spring can automatically bind its dependencies through class introspection so that you do not have to specify the properties and constructors of the bean. The Bean's properties can be automatically bound by property name or type matching. The constructor implements automatic binding through type matching. You can even specify that automatic binding mode is automatically detected, and it can guide spring to choose an appropriate running mechanism. Let's take a look at one of the following examples:

<bean id= "OrderService"
Class= "Com.lizjason.spring.OrderService"
Autowire= "ByName"/>

The property name of the OrderService class is used in the container to match the bean instance. Automatic binding can potentially save some typing and reduce some confusion. But in real-world engineering you should not use this approach because it sacrifices the clarity and maintainability of the configuration. Many of the guides and presentations tout automatic binding as an excellent feature of spring without mentioning the sacrifices of this feature. In my opinion, this is like the object-pooling in spring, which is more like a business feature to occupy more markets. It's a good way to compact XML configuration files, but it actually adds complexity, especially if you run a project with a large number of class declarations. Although spring allows you to mix automatic binding and manual binding, this paradox makes XML configuration more obscure.

  2. Use of popular naming

This approach works just as well for Java coding. The use of clear, descriptive, and coordinated popular names in engineering is useful for developers to understand XML configurations. For example, for a bean ID, you can name it according to the popular Java class name. For example, the Orderservicedao Bean ID is named Orderservicedao. For large projects, you can prefix the bean ID with the package name.

  3. Use a concise form

Simplicity avoids verbosity because it writes attribute values and references from child elements into attributes. For example, the following 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 concise form to:

<bean id= "OrderService"
class= "Com.lizjason.spring.OrderService" >
<property name= "CompanyName"
Value= "Lizjason"/>
<constructor-arg ref= "Orderdao"/>
</bean>

The concise form feature can be used in version 1.2. There is no concise form for <ref local= "..." >. Concise form not only can save your typing, but also make the XML configuration file clear. It is most noticeable when you have a large number of defined classes in a configuration file to improve legibility.

  4. For constructor parameters, the type name is better than the sequence number.

When a constructor contains more than one parameter of the same type, or if the label of the attribute value is already occupied, spring allows you to use the ordinal number from the 0 count to solve these confusing problems. For example:

<bean id= "BillingService"
class= "Com.lizjason.spring.BillingService" >
<constructor-arg index= "0" value= "Lizjason"/>
<constructor-arg index= "1" value= "/>"
</bean>

as follows, it is better to write with type attributes:

<bean id= "BillingService"
class= "Com.lizjason.spring.BillingService" >
<constructor-arg type= "Java.lang.String"
Value= "Lizjason"/>
<constructor-arg type= "int" value= "/>"
</bean>

Using indexes can reduce some of the verbosity slightly, but it is prone to error and difficult to read compared to using type attributes. You should only use indexing when the constructor parameters are ambiguous.

  5. Reuse the defined bean as much as possible

Spring provides an inheritance-like mechanism to reduce replication of configuration information and simplify XML configuration. Defines a subclass that can inherit configuration information from its parent class, and the parent class is essentially a template for subclasses. This is the so-called reuse in big projects. All you have to do is set up abstract=true in the parent bean and then note its own parent bean 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--lizjason of the CompanyName property from the Abstractservice class. If you don't specify a class or factory method for a bean, then the bean is abstract.

  6. Try to assemble the defined bean using ApplicationContext

Like references in an ant script, the spring reference is useful for assembling a modular bean. For example:

<beans>
<import resource= "Billingservices.xml"/>
<import resource= "Shippingservices.xml"/>
<bean id= "OrderService"
class= "Com.lizjason.spring.OrderService"/>
<beans>

It is more flexible to configure these beans by applicationcontext than by using import to preinstall in an XML configuration. The use of ApplicationContext also makes XML configuration easy to manage. You can arrange the bean in the Applictioncontext constructor as in the following example:

string[] Serviceresources =
{"Orderservices.xml",
"Billingservices.xml",
"Shippingservices.xml"};
ApplicationContext Orderservicecontext = new
Classpathxmlapplicationcontext (serviceresources);

  7. Use ID as the identifier of the bean

You can specify an ID or name to use as the bean identifier. Although using IDs does not improve readability, it allows XML parser to better validate the bean's references. If you cannot use an ID because of the limitations of the XML IDREF, you can use names as the bean identifier. The limitation of XML IDREF is that IDs must begin with a letter (or a punctuation mark defined in the XML specification), followed by letters, numbers, hyphens, underscores, colons, and so on. In fact, the problem of encountering XML IDREF constraints is very rare.

  8. Using dependency testing in the development phase

You can set a value in the bean for a dependent validation property, instead of the default null value, and property settings such as Simple,object or all so that the container relies on a test. Dependency checking is useful when all of the Bean's properties (or some sort of attribute) need to be explicitly set or automatically bound.

<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 properties set for the OrderService bean are not primitives or collections. It is also possible to set the default dependency detection for all beans, but we rarely do so because some bean properties do not have to be set at all.

 9. Add a header comment to each profile

It is best to use the descriptive ID and name instead of annotations in the XML configuration file. In addition, it is useful to add a header for the configuration file that outlines the beans defined in the file. You can choose to add the description to the description tag. 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 it is easy to use tools to select and remove description from the tag.

  10. For any change, to actively communicate with teammates

When you refactor Java code, you need to update the configuration file and notify your teammates at any time. XML configuration files are also code, they are a vital part of the application, but they are difficult to read and maintain. Most of the time you have to read the XML configuration file and read the running Java code.

  Setter injection superior to constructor injection

Spring provides 3 types of dependency Injection: constructor Injection,setter injection, and method injection. We generally use only the first two types.

<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, and the BillingService class uses setter injection. Constructor injection ensures that the bean is not created in an illegal state, but the setter injection is more flexible and manageable, especially if the class has many properties and some of them are optional.

  12. Do not misuse Dependency injection

As a last resort, Spring ApplicationContext can create Java objects for you, but not all Java objects are created by dependency injection. For example, global objects should not be created by ApplicationContext. Spring is a great framework, but in terms of readability and manageability, XML-based configuration issues can be highlighted when a large number of beans are defined. Excessive dependency injection can complicate and bloat the XML configuration. Remember! When using powerful Ides, such as Eclipse and IntelliJ, Java code is more readable, maintainable, and manageable than XML files.

  Summarize

XML is an excellent way to configure spring. But when you define a large number of beans, the xml-based configuration becomes tedious and cumbersome. Spring provides a wealth of configuration options. The appropriate use of the options in these can make the XML configuration clear, but some options, such as autowiring (automatic binding), tend to reduce readability and maintainability. The examples listed in this article can help you create a clearly readable XML configuration file.



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.