How to 13 Best Practices for Writing Spring Configuration Files

View: 166    Dowload: 0   Comment: 0   Post by: hanhga  
Author: none   Category: Javascript   Fields: Other

9 point/1 review File has been tested

Spring is a powerful Java application framework, used in a wide range of configuration options. Its best feature if that it provides enterprise services to Plain Old Java Objects (POJOs) called beans.

Introduction

Spring is a powerful Java application framework, used in a wide range of configuration options. Its best feature if that it provides enterprise services to Plain Old Java Objects (POJOs) called beans. Spring uses dependency injection (DI) to achieve simplification and increased testability. Spring beans, dependencies, and the services needed by beans are specified in xml configuration files or annotations. The XML configuration files, however, are verbose and more clean. If not planned and written correctly, it becomes very hard to manage in big projects. In this article, I will show you 10 best practices for writing spring XML configurations. Some of them may seem more necessary practices rather than best practices, yet I have included them in here because they were highly related to the topic.

1) Add a header comment to each configuration file

I always put more stress on code comments. The same goes for configuration files also. It is always very helpful to add a configuration file header, which summarizes the beans/properties defined in the configuration files.

In spring configuration, you can add comments as adding xml comments or you can use the description element. For example:

<beans>
    <description>
        This configuration file will have all beans 
        which may be used for controlling transactions.
    </description>
    ...
</beans>

One possible advantage of using the description tag is that some tools may pick up the description from this element to help you in other places.

2) Use consistent naming conventions

This is very important thing that you use same naming across all configuration files. Using clear, descriptive, and consistent name conventions across the project increase the readability of configuration files and make it easy for other developers to avoid some accidental bugs.

For bean ID, for example, you can follow the Java class field name convention. The bean ID for an instance of EmployeeUpdateDAO would be employeeUpdateDAO. For large projects, you can add the package name as the prefix of the bean ID. e.g. finance.employeeUpdateDAO.

3) No version numbers in schema references

I have also pointed out this feature earlier in previous post. I am again including it because it is essential and beneficial in long term specially to improve maintainability. To refresh your memory, specifying version number in bean configuration files for referenced schemas are not mandatory at all, and you can omit it. If fact, you should omit it all the time.

Spring automatically picks the highest version available from the project dependencies (jars). Also, as the project evolves and the Spring version will be updated, we won’t have to maintain all the XML config files to see the new features.

A sample example will be like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context/
  http://www.springframework.org/schema/context/spring-context.xsd">
  
  <!-- Other bean definitions-->
    
</beans>

4) Prefer setter injection over constructor injection

Spring provides three types of dependency injection: constructor injection, setter injection, and method injection. Usually, we all use first two types only.

<!-- Constructor injection -->
<bean id="employeeDAO"   class="com.howtodoinjava.dao.EmployeeDAO">
    <constructor-arg ref="datasource"/>
</bean>
 
<!-- Setter injection -->
<bean id="employeeDAO" class="com.howtodoinjava.dao.EmployeeDAO">
    <property name="datasource"  ref="datasource">
</bean>

Constructor injection can provide the cheapest thread safety possible i.e. immutable object. Also it guarantees that object will not be handed over to other beans without complete initialization.

Setter injection provides much desired capability i.e. flexibility or maintainability. If there are multiple attributes to set in a bean, then creating a long list of parameters to constructor is not good idea. Also, if is possible that some of the attributes might be optional.

Prefer flexibility. For immutability or thread safety, follow other programming rules.

Read More: How to make a java class immutable

5) Prefer type over index for constructor argument matching in Constructor injection

Better to avoid constructor injection and prefer to use setter injection for dependency injection. But, if you have an absolute requirement to use constructor injection then always prefer parameter matching based on type rather than index.

<!-- Index based constructor injection -->
<bean id="employeeDAO" class="com.howtodoinjava.EmployeeDAO">
    <constructor-arg index="0" value="rest"/>
    <constructor-arg index="1" value="8080"/>
</bean>
 
<!-- Type based constructor injection -->
<bean id="employeeDAO" class="com.howtodoinjava.EmployeeDAO">
    <constructor-arg type="java.lang.String" value="rest"/>
    <constructor-arg type="int" value="8080"/>
</bean>

As you can see that type based argument passing is more readable and less error prone. But, anytime there is any ambiguity in type based argument passing, go to index based argument passing without hesitation.

6) Use shortcut forms over expanded forms

Spring bean configuration semantics allow two forms for specifying property values and other bean references. One is expanded and other is shorter form. Prefer shorter version.

<!-- Expanded version -->
<bean id="employeeDAO" class="com.howtodoinjava.dao.EmployeeDAO">
    <property name="datasource">
        <ref bean="datasource"></ref>
        <value>datasource</value>
     </property>
</bean>
 
<!-- Shorter/shortcut version -->
<bean id="employeeDAO" class="com.howtodoinjava.dao.EmployeeDAO">
    <property name="datasource"  ref="datasource" value="datasource">
</bean>

7) Reuse bean definitions as much as possible

Spring provides a very useful capability which you should use extensively in your project and i.e. bean definition re-usability. Here I am not talking about bean references for setter injection. Rather I am pointing out the bean definition re-use in constructing other beans.

Take an example of datasource definition:

<bean id="abstractDataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close"
    p:driverClassName="${jdbc.driverClassName}"
    p:username="${jdbc.username}"
    p:password="${jdbc.password}" />
 
<bean id="concreteDataSourceOne"
    parent="abstractDataSource"
    p:url="${jdbc.databaseurlOne}"/>
  
<bean id="concreteDataSourceTwo"
    parent="abstractDataSource"
    p:url="${jdbc.databaseurlTwo}"/>

8) Always use ids as bean identifiers

Spring allows two types of identifiers for a bean. Using attribute “id” or by “name”. You should always choose attribute id over name. Usually it does neither increase readability nor benefit any performance scenario. It is just industry standard practice which all fellow developers are following worldwide and even in your team.

Just don’t be odd man out here.

9) Try to avoid autowiring

Autowiring is a great feature if you can manage it in long term. Usually it is beneficial if you project is having very few beans and you can almost remember them all in your memory as well.

As soon as project gets bigger, autowiring starts creating trouble in identifying correct dependency to use. The main drawback, I find is not to have a overview of whole system binded together. This is where spring configuration files win. They can represent the whole system to any new guy in couple of minutes.

Also, when you start debugging some complex issues then all information present in one place in configuration files, actually helps a lot. Autowiring makes debugging harder.

10) Always use classpath prefix

When importing resources, XML config, properties, etc. Always use the classpath: or classpath*: prefix. This provides consistency and clarity to the location of the resource. Not every feature of Spring behaves the same, classpath: guarantees consistency.

The classpath is determined by the build tool and IDE. Usually this is src/main/java for java code,src/main/resources for non-java dependencies and for tests, src/test/java for java code and src/test/resourcesfor non-java resources.

<!-- Always use classpath: prefix-->
<import resource="classpath:/META-INF/spring/applicationContext-security.xml"/>

11) Always externalize properties

Often there are multiple configuration parameters related to runtime of application. They are passed to bean definitions in bean configuration context file. DO not hard code them in config file. Instead externalize them to some properties file(s).

Better group them in separate files based on their usage or module i.e. all JDBC datasource related properties injdbc.properties file.

<bean id="abstractDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close"
        p:driverClassName="${jdbc.driverClassName}"
        p:username="${jdbc.username}"
        p:password="${jdbc.password}" />

and properties file

/* file://jdbc.properties */
 
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=password

12) Use dependency-check at the development phase

You should mostly set the dependency-check attribute on a bean definition to simpleobjects, or all (default value is none i.e. no checking), so that the container can do explicit dependency validation for you. It is useful when all of the properties (or certain categories of properties) of a bean must be set explicitly, or via autowiring.

<bean id="abstractDataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close"
    p:driverClassName="${jdbc.driverClassName}"
    p:username="${jdbc.username}"
    p:password="${jdbc.password}"
    dependency-check="all" />

In above given example, the container will ensure that all properties/parameters to datasource are set in application initialization time itself.

13) Do not abuse/overuse dependency injection

Finally, please do not abuse the motive behind introducing dependency injection. Java provide “new” keyword to create new objects. Use this wonderful keyword where DI is not necessary e.g. DTO objects. Don’t try to play smarter. Just follow the basics.

Drop me a comment if you feel otherwise on any of above points.

Happy Learning !!

 

How to 13 Best Practices for Writing Spring Configuration Files

How to 13 Best Practices for Writing Spring Configuration Files Posted on 10-08-2016  Spring is a powerful Java application framework, used in a wide range of configuration options. Its best feature if that it provides enterprise services to Plain Old Java Objects (POJOs) called beans. 9/10 166

Comment:

To comment you must be logged in members.

Files with category

  • JUnit 5 State Of The Union using java

    View: 629    Download: 0   Comment: 0   Author: none  

    JUnit 5 State Of The Union using java

    Category: Javascript
    Fields: Other

    1.5/3 review
    JUnit 5 has been under development for about 14 months now and the prototype is almost a year old. Time to summarize what happened so far, where the project stands, and where it’s going.

  • Getting Started with Dropwizard using java

    View: 731    Download: 0   Comment: 0   Author: none  

    Getting Started with Dropwizard using java

    Category: Javascript
    Fields: Other

    1.5/3 review
    Dropwizard is a framework for building RESTful web services in Java. In this tutorial we’re going to have a look at how to get started with developing a Dropwizard application by building a new service from scratch.

  • Build Query NULL Value in MySql

    View: 336    Download: 0   Comment: 0   Author: none  

    Build Query NULL Value in MySql

    Category: Javascript
    Fields: Other

    2.5/2 review
    Misunderstanding NULL is common mistake beginners do while writing MySql query. While quering in MySql they compare column name with NULL. In MySql NULL is nothing or in simple word it isUnknown Value so if you use comparison operator for NULL values...

  • Manage Your JavaScript Application State with MobX

    View: 355    Download: 0   Comment: 0   Author: none  

    Manage Your JavaScript Application State with MobX

    Category: Javascript
    Fields: Other

    2.25/2 review
    This article was peer reviewed by Michel Weststrate and Aaron Boyer. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

  • Build Bringing Pages to Life with the Web Animations API

    View: 359    Download: 0   Comment: 0   Author: none  

    Build Bringing Pages to Life with the Web Animations API

    Category: Javascript
    Fields: Other

    3/3 review
    This article is by guest author Dudley Storey. SitePoint guest posts aim to bring you engaging content from prominent writers and speakers of the JavaScript community.

  • How to Style Google Custom Search Manually

    View: 342    Download: 0   Comment: 0   Author: none  

    How to Style Google Custom Search Manually

    Category: Javascript
    Fields: Other

    0/0 review
    Website owners very often decide on using Google’s Custom Search Engine (GCSE) for searching through their content instead of using built-in and/or custom search functionality. The reason is simple – it’s much less work, and most often it does the...

  • Test React Components Using Jest

    View: 5113    Download: 0   Comment: 0   Author: none  

    Test React Components Using Jest

    Category: Javascript
    Fields: Other

    4.5/1 review
    This article is by guest author Jack Franklin. SitePoint guest posts aim to bring you engaging content from prominent writers and speakers of the JavaScript community.

  • Programming Question Reverse String without using String function

    View: 818    Download: 0   Comment: 0   Author: none  

    Programming Question Reverse String without using String function

    Category: Javascript
    Fields: Other

    4.5/1 review
    Write a program to reverse string without using string function. You don’t have to use any in-built string library function. This problem can be solved by multiple approaches. Let’s check it.

 

File suggestion for you

File top downloads

logo codetitle
Codetitle.com - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.com Develope by Vinagon .Ltd