- Wiegand.DK - https://www.wiegand.dk/wordpress -

#Enterprise #JAVA #paradigm / core framework – #Spring!

Enterprise JAVA paradigm / core framework – Spring!

There is a huge difference when you work on a personal project and when you work on an enterprise project. In your personal project it doesn’t really matter how you structure the code – the goal is to get it to work and everything else comes in second row. In an enterprise project you don’t know how long you are going to work on the project, who is going to take over, will it be send to India, etc. In an enterprise project you are not a one-man army but a team and the team members will be replaced many times over the projects lifespan. Therefore you need a common ground – a paradigm that state how members in the team should behave, what a new team member should expect and especially what is expected of a member of the team when contributing to the project.

The paradigm sets up the arena – the context – the rules that describe where “things” can be found. If you deviate from the paradigm “things” will be lost! A paradigm must be both simple and fulfilling – to grasp over the variety of an enterprise application.

When googling JAVA and core frameworks a lot of different kind of frameworks turn op.  Most of the frameworks have only one goal (construct a GUI, interact with the database, fast prototyping, etc.) and therefore a lot of limitations.

The people behind JAVA have of cause made their version of a paradigm with JAVA enterprise (JEE – http://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition [1]). Calling it a paradigm is definitely being too nice. It is a collection of intensions of how to handle “enterprise” problems and then it is up to some vendor to implement these intentions. All the “big” vendors have made an implementation of JEE and of cause applied their add-ons that unfortunate (for the most) makes it hard to run on other application servers than their own.

Most of the other all-round frameworks have more focus on fast prototyping and locked paradigms that don’t leave much space for introduction of new APIs or switching of core components. The framework end op fighting against your innovation and of the use of best-of-breed (http://en.wikipedia.org/wiki/Best_of_Breed [2]) on the market. A framework should be your friend – not your enemy.

The only JAVA framework that gives the project enough freedom, that is vendor “independent”, that have a large portfolio of core modules and that is widely used – is the spring framework (http://spring.io [3]). It is easy to find information (if you are stuck or in need of inspiration) as well as getting developers (all over the world).

In my opinion spring is not enough to achieve a good paradigm. With spring you will have some order in your code but where should the JAVA source files be placed, where should the test cases be places, where should the configuration be placed, where should the compiled files be places, how should third party libraries be handled, etc.

Again there are some tools out there that can help you. The important thing is to select one tool that can do the magic for you – that can set a standard on how this should be done and that not in need of a lot of small tools to fulfill your goals.

It can be done with ANT (http://en.wikipedia.org/wiki/Apache_Ant [4]) but you have to introduce a lot of small tools to get the complete package and there is not a common suite. This means that you can’t expect when you come to a new project that uses ANT that “thing” are placed in the same order as on your previous ANT project.

Maven (http://en.wikipedia.org/wiki/Apache_Maven [5]) has the complete package and is widely used. You have to make an effort to deviate from the standard and it is just easier to use it correct. Maven is a dictatorship and that is a good thing when contributing to an enterprise project as a team member.

A good place to start with maven is here: http://refcardz.dzone.com/refcardz/apache-maven-2 [6]

Note: One thing is the internal structure of your enterprise project another thing is how you share information between projects. I will hopefully write a blog on this in the future to give you the insight on how this can ease your life a lot.

The project file structure in maven is dictated as below and sets a nice common standard on where to find things.

root
	src/main/java		(Your application code)
	src/main/resources	(Your configuration)
	src/main/webapp 	(Your web root)
	src/test/java		(JUnits and JAVA runners)
	src/test/resources	(Test configuration)
	target			(Build directory)
	pom.xml			(Maven build file)

I addition to the standard maven folders I always add some extra to keep needed information close to the project. Then the developer shouldn’t need to gain access to some obscure system or drive and try to retrieve the needed information just to get started.

root
	Documentation		(Documentation needed to understand the project)
	Releases		(Information of releases; notes, database scripts, etc.)

Every thing that can be automated should be automated and executed through maven – then the developer only have to look one place regarding build, deployment, release, test, etc.

Spring

Like all other frameworks spring don’t master everything but it provides a very good foundation, a lot of standard modules and a high degree of freedom. It works great together with JAVA enterprise standards such as JPA (http://en.wikipedia.org/wiki/Java_Persistence_API [7]) , JTA (http://en.wikipedia.org/wiki/Java_Transaction_API [8]), etc. and because spring is widespread used a lot of third-party vendors have spring-enabled their projects.

Spring is at its core very simple. You create a (spring) context that embraces your application. Then you create (spring) beans and bind these beans together in chains to solve a given use case. This doesn’t sound so hard but there is of cause some magic you have to provide before you get to the fun part of creating you business logic.

The context

Once the spring context has been setup you can start spring in a lot of different ways. I have worked with spring in very different structured projects that needed their own approach of how to start and setting op the context.

Note: You can run into situations where the context is started twice and you therefore have two instances of every spring bean. It will give you a lot of errors by time and hours of fun debugging trying to understand what the hell is going on. Beware of this and introduce a context factory to solve the problem if you run into it.

The most common scenario and 95% of the projects I run into is the web-enabled application. A web-enabled application contains web services, a GUI tier, a business logic tear, a data access tier and a data tier. The application will for the most be activated by a web request but most applications will also have the need to execute scheduled tasks.

The target of the application is an application server like Tomcat (http://tomcat.apache.org [9]), WebLogic (http://en.wikipedia.org/wiki/Oracle_WebLogic_Server [10]) or Websphere (http://en.wikipedia.org/wiki/IBM_WebSphere [11]). When building the application for an application server the packing must be a WAR (http://en.wikipedia.org/wiki/WAR_(file_format) [12]) or EAR (http://en.wikipedia.org/wiki/EAR_(file_format) [13]) file containing all information needed to execute the application.

Note: If you have more than one WAR file in you EAR file you need to use a context factory in order not to instantiate the context more than once.

In the WAR file you setup the context in the web.xml configuration file. The web.xml file is the main configuration file and where you should put your configuration regarding the WAR file. A team member should be able to find all core mounts like servlets, web service (REST, RPC, etc.), frameworks (Spring, Wicket, etc.), … the point is: Don’t confuse the team members by hiding functionality in the code or “hidden” configuration files.

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app
	xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:web=http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:/spring/application_context.xml</param-value>
	</context-param>

	<!-- ... -->

</web-app>

There are two very important things done in the web.xml. The first is that spring is instantiated with the class [org.springframework.web.context.ContextLoaderListener]. The second is that I don’t use the default location for the spring context configuration. I like defaults but if you don’t know what defaults are – things can be hard to find. Another thing is that I want to state that I have decided where the configuration is placed and I want to place the entire configuration to the application in the same folder – again there is only one place to look.

The default location of the context configuration is in the WEB-INF folder and the file is called applicationContext.xml. The [contextConfigLocation=classpath:/spring/application_context.xml] above is minded on a maven setup where all configurations are placed in [src/main/resources]. If the build were done with ANT I would place the context configuration in [WEB-INF/spring/application_context.xml].

Note: The web.xml above is based on version 2.5. Web.xml is structured differently in previous versions.

Spring context configuration

The main spring configuration can be done both in JAVA and in XML. I prefer the XML configuration to separate the general configuration of maven from the application source code. Then there is not confusion on where to place the configuration and especially where to find the configuration. The most common way to configure maven is by XML and therefore a good choice.

I divide the maven context configuration up in a main file and separate files for different areas.

The main file functions as an index for the context configuration and contains only references to the area files. I call the main file application_context.xml. The context below includes two other context files. A common context file handles the common configuration of the application and a database context file handles the database configuration area of the application.

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns=http://www.springframework.org/schema/beans
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans<
		http://www.springframework.org/schema/beans/spring-beans.xsd">
	<import resource="application_context_default.xml" />
	<import resource="application_context_database.xml" />
</beans>

It is not a good ide to split up the configuration in atoms like files. Keep the simple/common configuration in a single file to ease the overview. If an area gets too big you can introduce a new configuration file containing that area – like the database area.

Below is a minimum common configuration file for an enterprise project.

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

	<context:component-scan base-package="dk.northtech.someproject" />

	<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
		<property name="corePoolSize" value="5" />
		<property name="maxPoolSize" value="10" />
		<property name="queueCapacity" value="25" />
	</bean>

	<bean id="taskScheduler" class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
		<property name="poolSize" value="5" />
		<property name="waitForTasksToCompleteOnShutdown" value="true" />
	</bean>
	<task:annotation-driven executor="taskScheduler" />

</beans>

A quick run-trough of what my common context configuration contains.

All areas of spring have their own XML schema and that schema must be included in order to handle the wanted area. I have included the 3 areas; bean, context and task – but there are a lot more and also a lot of third party areas that can be included as well.

In order to find spring component annotations (beans) in your application code you need to scan your project base package – in this case: dk.northtech.someproject. All classes annotated with component, repository, service, etc. are now available as spring beans and reachable in the spring application context.

The two beans below the component scan setup a central task executor and a task scheduler. Now it is possible in your application to execute tasks that you don’t want to impact your session thread and to schedule batch and cleanup jobs.

An extra twist for the task scheduler is the statement that it also can be annotation driven. This means that you can add the annotation @Scheduled to a given method in a spring bean and now that method is scheduled. For example if you want to reload your configuration every hour you just have to implement a method that reload the configuration and add the annotation @Scheduled(cron=”0 0 * * * ?”).

If you want to call the executer or the scheduler by hand from a bean you just need to inject them (http://en.wikipedia.org/wiki/Dependency_injection [14]).  To inject beans in spring you have to use the @Autowired annotation then spring will look in the context if there is a been with the given name or if there is a bean that implements the given name. If there is more than one implementation you need to indicate the wanted implementation by adding the annotation @Qualifier(“myImplementation”) as well or instead use the annotation @Resource(name = “myImplementation”). A better choice would be to state on the desired bean, which one is the primary implementation with the annotation @Primary, and then only add the qualifier when deviating from the standard.

@Service
public class MyServiceImpl implements MyService {

	@Autowired
	private TaskExecutor taskExecutor;

	@Override
	public void executeSomething() {
		taskExecutor.execute(new MyTask());
	}

	@Autowired
	private TaskScheduler taskScheduler;

	@PostConstruct
	public void scheduleSomething() {
		taskScheduler.schedule(new MyTask(), new CronTrigger("0 0 * * * ?"));
	}

}

public class MyTask implements Runnable {

	public MyTask() {
	}

	@Override
	public void run() {
		// Do something
	}

}

The database configuration contains a bit more magic. I want to use JPA2 to access the database and I want Hibernate as the implementation – see How to build a #domainmodel with #JPA2 and #Hibernate. I don’t want to state a specific database in my application but only the name of the data source that I expect to be available when needed. Further more I want to be able to go around JPA2 if direct access is needed to the database.

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://www.springframework.org/schema/jee
		http://www.springframework.org/schema/jee/spring-jee-3.0.xsd"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xmlns:jee="http://www.springframework.org/schema/jee">

	<!-- Data source -->
	<jee:jndi-lookup id="myDataSource" jndi-name="MY_DATA_SOURCE" default-ref="myTestDataSource" />

	<!-- Test data source -->
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:/liquibase/liquibase.properties" />
		<property name="ignoreUnresolvablePlaceholders" value="true" />
	</bean>

	<bean id="myTestDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		<property name="driverClass">
			<value>${driver}</value>
		</property>
		<property name="jdbcUrl">
			<value>${url}</value>
		</property>
		<property name="properties">
			<props>
				<prop key="c3p0.acquire_increment">5</prop>
				<prop key="c3p0.idle_test_period">100</prop>
				<prop key="c3p0.max_size">100</prop>
				<prop key="c3p0.max_statements">0</prop>
				<prop key="c3p0.min_size">10</prop>
				<prop key="user">${username}</prop>
				<prop key="password">${password}</prop>
			</props>
		</property>
	</bean>

	<!-- Spring JDBC template -->
	<bean id="myJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" primary="true">
		<constructor-arg ref="myDataSource" />
	</bean>

	<!-- JPA2 / Hibernate -->
	<bean name="hibernateJpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
	<bean name="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
	<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
	<bean id="myEntityManagerFactory" primary="true" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="jpaDialect" ref="hibernateJpaDialect" />
		<property name="packagesToScan" value="dk.northtech.someproject.domainmodel" />
		<property name="persistenceUnitName" value="myPersistenceUnit" />
		<property name="dataSource" ref="myDataSource" />
		<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
		<property name="jpaProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
				<prop key="hibernate.show_sql">false</prop>
				<prop key="hibernate.format_sql">false</prop>
			</props>
		</property>
	</bean>

	<bean id="myTransactionManager" primary="true">
		<property name="jpaDialect" ref="hibernateJpaDialect" />
		<property name="entityManagerFactory" ref="myEntityManagerFactory" />
	</bean>

	<tx:annotation-driven transaction-manager="myTransactionManager" proxy-target-class="true" />

	<!-- Spring direct transaction access -->
	<bean id="myTransactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" primary="true">
		<property name="transactionManager" ref="myTransactionManager" />
		<property name="propagationBehaviorName" value="PROPAGATION_REQUIRED" />
		<property name="readOnly" value="false" />
	</bean>

	<!-- Liquibase -->
	<bean id="liquibase" class="liquibase.integration.spring.SpringLiquibase">
		<property name="dataSource" ref="myDataSource" />
		<property name="changeLog" value="classpath:/liquibase/changelog-master.xml" />
	</bean>

</beans>

I will not go into all the details in the configuration but just state the essentials.

Data source and test data source

I expect to find a data source called MY_DATA_SOURCE. The data source name should of cause reflect the application name and NOT be a general name when you create your application. I have added a default test data source if the MY_DATA_SOURCE is not available. This is a nice thing to have when testing but beware of this when going into production. Mostly I remove this when going into production – it depends on the project. The connection properties to the test data source are places in an external property file based on the Liquibase database framework (http://www.liquibase.org [15]). This is in my opinion the best framework to handle database changes in an enterprise environment. I hope to write a blog on Liquibase and how to use it in an enterprise application later.

JDBC template

In order to just execute stuff directly at the data source I have introduced the spring JDBC template. Sometimes JPA is not the way to go because of a big overhead and then it should be possible to execute database functionality directly.

JPA2 and Hibernate

Spring needs to instantiate hibernate and state that hibernate is used as the JPA2 implementation. Basically you need to look at two properties.

The first property states where JPA2 expects to find the domain model (the entities) – packagesToScan. In this case the package dk.northtech.someproject.domainmodel must contain the domain model.

The second property adds vendor specific (hibernate) properties. This is where you state the concrete database vendor you want to use (PostgreSQL, MS SQL Server, DB2, Oracle, etc.). This is also where you enable one of the most important debug and profiling features – enabling/disabling of SQL output. This is how you ensure that Hibernate doesn’t turn your application into an erupting volcano that spits out SQL in every direction as hot lava.

The last thing that is nice to notice is that transaction management is annotation enabled. Now you can add the transactions handling directly in your repositories (DAOs).

Direct transaction access

As the JDBC template it is sometimes needed to have directly access to the current transaction and add database specific calls that you don’t want to be JPA2. This is possible with the spring transaction template.

Liquibase

When you base the handling of the data model on Liquibase you can get the application to handle the updates of the database directly. This is NOT always the way to do it but it is a need way of letting the application handle the versioning of the data model directly. When working for big enterprises there need to be 100% control with the data model as scripting are advised in this case but in small projects it is a very big help. You just provide the WAR or EAR file and then Liquibase do the rest.

The structure of your source code

It is all about the expectations! There is not one common way of structuring your packages but you can ease it for your team members by using common designations.

Your application will for the most contain a domain model – the business area you are handling. You will probably have a database storage and thereby some data access object that will handle the transitioning. You will write your business logic where you provide manipulation of the domain model. Furthermore you will have some web services so your javascript GUI and other application can interact with your application. And maybe you have an old server-side rendered GUI.

The domain model (http://en.wikipedia.org/wiki/Domain_model [16]) is a well-understood way of handling business area and therefore a good name to state that in this package you will find the domain model of the application.

Spring has provided a common way of handling DAOs and business logic. DAOs are places in repositories and business logic are provided as services.

When exposing web services to the world it would be nice to know where to look for the implementation and what to expect when looking at the service. What kind of web service are we looking at? What should be our mindset when look at the implementation. When doing a web service exposing your application and the team members should not be in doubt where this is done and of cause be extra careful in this area of the code.

The package structure I use looks like this.

dk.northtech.someproject		(base package)
	domain model			(The domain model)
	repository			(The data access layer)
	service				(The business logic)
	task				(Scheduled and async tasks)
	webservice			(Web services)
		rest			(REST web services)
		rpc			(RPC web services)
	ApplicationConfiguration.java	(Application constants)

With this structure you know where to look for “things” and what you can expect when looking in one of the packages. It is up to the given application to decide when to add sub packages if the file count gets too high.

Note: If you must have a server-side rendered GUI I would put that in a package called dk.northtech.someproject.gui. Furthermore I would state the GUI framework you as a package as well. If you have chosen Apache Wicket the package would be named dk.northtech.someproject.gui.wicket.

Spring components

To add a class to the spring context as a spring component / spring bean you must either annotate it or define it in the XML configuration. Components specific for your application should be annotated – but general utilities should be configured in the XML configuration.

The general spring bean annotation is called @component and spring has created three derived annotations called @Service, @Controller and @Repository to indicate the purpose of the given bean.

Note: All spring beans are by default singleton. Only one instance of the class is created and inserted into the spring context. This means that attribute on a spring bean will act as statics. You can of cause define that you a new instance but more likely you should use one of your domain objects or a value object to contain the data.

The general component annotation is used for helpers and utilities that are specific for your application. I you use third-party utilities (or your companies own external utilities) they should be defined in the spring XML configuration. Then the team members know where to expect to find the configuration for used utilities in the application.

As earlier mentioned service is the spring word for business logic and repository the word for DAO. Service and repository should be placed in the matching packages and sub packages. Now it is possible to find the business logic and DAOs by browsing but also when searching for @Service or @Repository. The easier it is to locate the key components the less effort a new team member must use to get into a project and start contributing.

The controller component is associated with the spring MVC (http://en.wikipedia.org/wiki/Model–view–controller [17]) framework. With spring MVC your can use it as a normal server-side framework that produce HTML pages, but you can also use it to create a REST web service. I have not used spring MVC to create REST web services and I don’t have an opinion if it is good or bad to handle REST web services.

In the last couple of years I have worked with goal of moving away from server-side GUI frameworks to a javascript application that communicates with the server through REST web services. In this process I have noted some key features.

The first thing is that it is important not to hide mounts (http://en.wikipedia.org/wiki/Mount_(Unix) [18]) in your application. A mount is for example the URL address to a servlet or a base mount on where to find REST web services. These mounts can be shattered throughout the code or centralized as they original was intended – in the web.xml in the WAR file. When you look at a WAR file you know that the base configuration is placed in the web.xml file and if your expectation is to find it here – it should be placed here. So when working with REST web services; either state the individual REST web service mount or the base mount in the web.xml file. I like to state the base REST web service mount in the web.xml file and place the code in the .webservice.rest package where you can find the individual REST web service mounts.

The second thing is to use a strict REST web service framework. You can do REST in a million different ways but when working on a team you want to do it the same way every time and you want to make is easy to create new web services. In my search on how to handle REST web services I constructed my own framework together with my company (http://www.northtech.dk/ [19]). The goal was to make REST web service is in three simple steps:

  1. A base mount in web.xml.
  2. A REST handle where it is possible to mount web services – restHandler.registerRestArea(…) 🙂  – where each area has five methods; list, create, read, update and delete (CRUD).
  3. A processor that processes the incoming request upholds the REST standard and provides simple error handling.

You can find NorthTech REST handler here: http://m2.northtech.dk/index.html#nexus-search;quick~northtech-net-extension [20]

I will write a blog on REST web services – how we did it – and take a look at how it can be done with JAX-RS (http://en.wikipedia.org/wiki/Java_API_for_RESTful_Web_Services [21]) or rest.li (http://rest.li/ [22]).

Calling spring beans outside spring

A notion with spring is that the annotation configuration only works within a spring bean. In a class not managed by spring you need to retrieve the spring context and first then you can get the desired bean. Spring only takes care of spring-enabled components and there is no need to scan all non-spring classes in search of spring annotations.

But why call spring from a non-spring class? The main reason for this is when you working on your enterprise web application and want to introduce a web service of a kind. You can use some build-in functionality in spring but maybe there is a better and easier framework out there that supports your needs and that framework may of may not be spring-enabled. In my case I have for the most the need of a simple and easy lightweight REST framework and a simple and easy RPC framework where the REST approach doesn’t apply.

Spring has made a helper (http://docs.spring.io/spring/docs/4.1.0.BUILD-SNAPSHOT/javadoc-api/org/springframework/web/context/support/SpringBeanAutowiringSupport.html [23]) that can ease the problem. The helper searches a given class for spring annotations and apply content accordingly. This means that you can annotate a given class with @Autowired and then the helper will inject the wanted spring components.

public class MyPojo {

	@Autowired
	private BusinessLogicService businessLogicService;

	public MyPojo() {
		SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
	}

	public void doSometing() {
		businessLogicService.doSomething();
	}

}

There are many solutions on how to get the spring context and call a bean but I like the approach above because you have to do same stuff as you would if you were working with a spring managed component. The differences are that the given class is NOT a spring bean and that you have to call the helper before the auto-wiring is done. The call is mostly done in the constructor but you can do it whenever you like.

Note: The helper does of cause not work when working on static classes.

Testing

When working on an enterprise project testing is the key. If you have good test coverage in your application you make it easy for a team member add new features and do refactoring. A core element in a good paradigm is that it is easy to test! Spring have worked a lot with how to make testing easy unlike the most of the JEE world. The JEE technologies can be tested easily but it is a demanding setup for most of the frameworks.

Just doing JUnits aren’t enough! When testing you must of cause have the mandatory JUnits but more importantly is the interface testing. Does the database behave, as it should? Does the REST web service behave, as it should? Does the business logic behave, as it should?

You can “avoid” a lot of these tests with the use of a mocking test framework (http://en.wikipedia.org/wiki/Mock_object [24]). Then you test the “intention” but not the actual functionality. Sometime the intention is good enough – for example when you are testing a servlet you don’t always need to test if the servlet actually works as it is specified. I use mocking in some cases and have grown fund of mockito (https://code.google.com/p/mockito/ [25]) to do the job.

When choosing a paradigm and frameworks an important part is that they are easy to test and that they provide functionality that make them easy to test. A paradigm or framework that provide test helpers is more likely to be enterprise ready – they know that test should be and is an integrated part of an application.

Spring provides integration to JUnit that creates the spring context (once!) and thereafter you can do dependency injection directly in the JUnit. You can quickly test your business logic.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {ApplicationConfiguration.SPRING_CONTEXT})
public class TestService {

	@Autowired
	private MyService myService;

	@Test
	public void testBusinesLogicA() {
		// ..
	}

	@Test
	public void testBusinesLogicB() {
		// ...
	}

}

The test above uses the spring JUnit runner and points to the spring context that is defined in the ApplicationConfigucation class.

This is my take on how an enterprise paradigm should look like. Please provide input if you know of a better way of handling the problem or if you have some adjustments.

Best Regards

Rolf Wiegand Storgaard