Friday, September 11, 2015

Using log MDC in multi-thread - Hello World example

The slf4j has MDC which will  delegate to underlying logging system's MDC implementation.  The most popular logging systems are log4j and logback. They both support MDC. So the most common way to use MDC (or logging system) is through slf4j API. In this demo, logback is used as underline logging system.

What can MDC(Mapped Diagnostic Context) do for me?

MDC is a map like structure, it can save information you want to output to the log, so you don’t need add that information to every logger.info(…) as parameter. For example, in an web application, you want every log output contain http request source IP. The IP string don’t need to be added to every logger call , or passed back and forth between controller and service layers. You should save that IP in the MDC, and use %X{IP} in log configuration to add that value to every line of your log output.

BTW, MDC is thread-safe. No worrying for concurrency.

MDC in multi-thread environment

In multi-thread environment, if the child is create with the basic Thread + Runnable way, the child thread will automatically inherit parent’s MDC. But if  using executor as thread management. The MDC inheritance is not  warranted, as the logback document said:

A copy of the mapped diagnostic context can not always be inherited by worker threads from the initiating thread. This is the case when java.util.concurrent.Executors is used for thread management.

In this hello world demo, there are 2 threads. The main thread will create a child thread using package java.utils.concurrent instead of the old style Thread way to show how to keep MDC context inheritance.

0. What you need

  • JDK 1.7
  • Maven 3.2.1
  • SLF4J 1.7.7
  • Logback 1.1.2

1. Configure the maven pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.shengwang.demo</groupId>
<artifactId>slf4j-logback-mdc</artifactId>
<version>1.0</version>
<packaging>jar</packaging>

<name>slf4j-logback-mdc</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>

Add dependencies for slf4j and logback in pom.xml

2. Define the Java class


There are 2 classes in this demo. First the Child.java.

package com.shengwang.demo;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

public class Child implements Runnable {
private Logger logger = LoggerFactory.getLogger(Child.class);

// contextMap is set when new Child() is called
private Map<String,String> contextMap = MDC.getCopyOfContextMap();

public void run() {
MDC.setContextMap(contextMap); // set contextMap when thread start
logger.info("Running in the child thread");
}
}

The Child.java is very simple, just implements the Runnable interface. One thing need to mention is how the MDC context is passed from parent thread to child thread. The Child object instance is created in parent thread, when new Child() is call immediately before executor create new thread. So the parent’s MDC context is duplicated to a variable called contextMap, then set back to MDC in child thread at the begin of run() method.


The Parent.java with main()

package com.shengwang.demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

public class Parent {
private Logger logger = LoggerFactory.getLogger(Parent.class);
private ExecutorService executorService = Executors.newCachedThreadPool();

public Parent() {
// Mimic Web app, save common info in MDC
MDC.put("IP", "192.168.1.1");
}

public void runMultiThreadByExecutor() throws InterruptedException {
logger.info("Before start child thread");

executorService.submit(new Child());
logger.info("After start child thread");

executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.SECONDS);
logger.info("ExecutorService is over");
}

public static void main(String[] args) throws InterruptedException {
Parent parent = new Parent();
parent.runMultiThreadByExecutor(); //MDC OK
}
}

In Parent class, ExecutorService from java.util.concurrency package is used to create a new child thread.  In parent’s constructor , String “192.168.1.1” has been put in MDC with key “IP”. The key/value can be any String. MDC works just like an ordinary Map<String,String>. It will be used in logback’s patten layout shown below.


3. Configure logging system to use values in MDC


In logback, the value can be get using "%X{KEY}" in appender’s pattern. So in this demo, it should be "%X{IP}". Here is the logback.xml for this demo.

<configuration>
<!-- to screen -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!-- screen output pattern -->
<pattern>%d{HH:mm:ss.SSS} [%X{IP}] [%thread] %-5level [%F:%L] - %msg %n</pattern>
</encoder>
</appender>

<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

Everything is almost done now. Let's review the directory structure for our maven project.


image


4. Run the demo


image


As we can see from the output, the information in MDC has been added to all output lines from both parent and child threads.

Thursday, September 10, 2015

How to invoke an object’s private method in Java

The private methods are designed not accessible from outside. But sometimes we want to call it directly, for example in unit testing. Java actually provides ways to call private method with the help of reflection, java.lang.reflect.Method

PowerMock, a widely used mock library also provide helper class to make it easy  in JUnit test cases. (PowerMock indeed wraps the reflection for you)

In this demo, there is a HellowWorld class under test.

package com.shengwang.demo;

public class HelloWorld {

private String sayHello(String name) {
return = "Dear " + name;
}
}

The private method sayHello will be tested in JUnit test case.


1. Method-1 Using reflection directly


  1. 1 What you need

  • JDK  (no third party library is required )

  1.2 Invoke private method in testcase

package com.shengwang.demo;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.junit.Test;


public class HelloWorldByReflectionTest {

@Test
public void testPrivateMethod() {
try {
HelloWorld helloWorld = new HelloWorld();
Method method;
// get reflected method
method = HelloWorld.class.getDeclaredMethod("sayHello",new Class[] { String.class });
// change accessiblity
method.setAccessible(true);
// invoke the method
assertEquals("Dear Tom", method.invoke(helloWorld, "Tom"));
} catch (NoSuchMethodException | SecurityException |
IllegalAccessException | IllegalArgumentException |
InvocationTargetException e) {
e.printStackTrace();
fail();
}
}
}

2. Method-2 Using PowerMock


  2. 1 What you need

  • Mockito
  • PowerMock

PowerMock usually need to work with either Mockito or EasyMock, you can choose anyone. In this demo Mockito is used.

2.2 Add Maven dependencies


Add dependencies to the maven pom.xml

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.5.6</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.5.6</version>
<scope>test</scope>
</dependency>

  2.3 Invoke private method in testcase

package com.shengwang.demo;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.powermock.reflect.Whitebox.invokeMethod;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ HelloWorld.class })
public class HelloWorldByPowerMockTest {
@Test
public void testPrivateMethod() {
String result;
try {
HelloWorld helloWorld = new HelloWorld();
result = invokeMethod(helloWorld, "sayHello", "Tom");
assertEquals("Dear Tom", result);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
}

The org.powermock.reflect.Whitebox.invokeMethod from PowerMock is imported at the beginning and used to invoke private method.

Tuesday, September 1, 2015

HTML Tags for JavaServer Faces (JSF)

The HTML Tags in for JSF is mostly used tags when writing JSF page. They are listed here for quick reference. The table comes from oracle JEE7 documents here.

Tag

Functions

Rendered As

Appearance

h:column

Represents a column of data in a data component

A column of data in an HTML table

A column in a table

h:commandButton

Submits a form to the application

An HTML <input type=value> element for which the type value can be"submit", "reset", or "image"

A button

h:commandLink

Links to another page or location on a page

An HTML <a href> element

A link

h:dataTable

Represents a data wrapper

An HTML <table> element

A table that can be updated dynamically

h:form

Represents an input form (inner tags of the form receive the data that will be submitted with the form)

An HTML <form> element

No appearance

h:graphicImage

Displays an image

An HTML <img> element

An image

h:inputFile

Allows a user to upload a file

An HTML <input type="file"> element

A field with a Browse... button

h:inputHidden

Allows a page author to include a hidden variable in a page

An HTML <input type="hidden">element

No appearance

h:inputSecret

Allows a user to input a string without the actual string appearing in the field

An HTML <input type="password">element

A field that displays a row of characters instead of the actual string entered

h:inputText

Allows a user to input a string

An HTML <input type="text"> element

A field

h:inputTextarea

Allows a user to enter a multiline string

An HTML <textarea> element

A multirow field

h:message

Displays a localized message

An HTML <span> tag if styles are used

A text string

h:messages

Displays localized messages

A set of HTML <span> tags if styles are used

A text string

h:outputFormat

Displays a formatted message

Plain text

Plain text

h:outputLabel

Displays a nested component as a label for a specified input field

An HTML <label> element

Plain text

h:outputLink

Links to another page or location on a page without generating an action event

An HTML <a> element

A link

h:outputText

Displays a line of text

Plain text

Plain text

h:panelGrid

Displays a table

An HTML <table> element with <tr>and <td> elements

A table

h:panelGroup

Groups a set of components under one parent

A HTML <div> or <span> element

A row in a table

h:selectBooleanCheckbox

Allows a user to change the value of a Boolean choice

An HTML <input type="checkbox">element

A check box

h:selectManyCheckbox

Displays a set of check boxes from which the user can select multiple values

A set of HTML <input> elements of type checkbox

A group of check boxes

h:selectManyListbox

Allows a user to select multiple items from a set of items all displayed at once

An HTML <select> element

A box

h:selectManyMenu

Allows a user to select multiple items from a set of items

An HTML <select> element

A menu

h:selectOneListbox

Allows a user to select one item from a set of items all displayed at once

An HTML <select> element

A box

h:selectOneMenu

Allows a user to select one item from a set of items

An HTML <select> element

A menu

h:selectOneRadio

Allows a user to select one item from a set of items

An HTML <input type="radio">element

A group of options

Wednesday, August 19, 2015

Maven Dependencies for JEE 7

A brief maven dependencies list for JEE7 related applications. The table below originally published by glassfish wiki

Component maven
Java EE 7 Full Platform JSR 342

<dependency>
   <groupId>javax</groupId> 
    <artifactId>javaee-api</artifactId> 
    <version>7.0</version>
</dependency>

Java EE 7 Web Profie

<dependency>
   <groupId>javax</groupId>  
    <artifactId>javaee-web-api</artifactId>  
    <version>7.0</version>
</dependency>

Concurrency Utilities for Java EE (JSR 236)

<dependency>
    <groupId>javax.enterprise.concurrent</groupId>
    <artifactId>javax.enterprise.concurrent-api</artifactId>
    <version>1.0</version>      
</dependency>

Java Persistence API 2.1 (JSR 338)

<dependency>
  <groupId>org.eclipse.persistence</groupId>
    <artifactId>javax.persistence</artifactId>
    <version>2.1.0</version></dependency>

Java API for RESTful Web Services 2.0 (JSR 339)

<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.0</version>
</dependency>

Servlets 3.1 (JSR 340)

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>

Expression Language 3.0 (JSR 341)

<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>3.0.0</version>
<dependency>

Java Message Service 2.0 (JSR 343)

<dependency>
    <groupId>javax.jms</groupId>
    <artifactId>javax.jms-api</artifactId>
    <version>2.0</version>
</dependency>

JavaServer Faces 2.2 (JSR 344)

<dependency>
    <groupId>javax.faces</groupId>
    <artifactId>javax.faces-api</artifactId>
    <version>2.2</version>
</dependency>

Enterprise JavaBeans 3.2 (JSR 345)

<dependency>
    <groupId>javax.ejb</groupId>
    <artifactId>javax.ejb-api</artifactId>
    <version>3.2</version>
</dependency>

Context & Dependency Injection 1.1 (JSR 346)

<dependency>
    <groupId>javax.enterprise</groupId>
    <artifactId>cdi-api</artifactId>
    <version>1.1</version>
</dependency>

Bean Validation 1.1 (JSR 349)

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>

Batch Applications for the Java Platform (JSR 352)

<dependency>
    <groupId>javax.batch</groupId>
    <artifactId>javax.batch-api</artifactId>
    <version>1.0</version>
</dependency>

Java API for JSON Processing (JSR 353)

<dependency>
    <groupId>javax.json</groupId>
    <artifactId>javax.json-api</artifactId>
    <version>1.0</version>
</dependency>

Java API for WebSocket (JSR 356)

<dependency>
    <groupId>javax.websocket</groupId>
    <artifactId>javax.websocket-api</artifactId>
    <version>1.0</version>          
</dependency>

Java Transaction API 1.2 (JSR 907)

<dependency>
    <groupId>javax.transaction</groupId>
    <artifactId>javax.transaction-api</artifactId>
    <version>1.2</version>           
</dependency>

Java EE Connector Architecture 1.7  (JSR 322)

<dependency>
  <groupId>javax.resource</groupId>
  <artifactId>javax.resource-api</artifactId>
  <version>1.7</version>
</dependency>

Thursday, August 6, 2015

Understand web.xml in Spring MVC project

The deployment descriptor file web.xml is the entry point to understand all configurations for a Spring MVC project.

In many cases, there are 2 type of  xml configuration files in a Spring MVC project:

  • web.xml – Describe how to deploy the web application to any Java Servlet container.
  • context configuration xml – Configuration file to create Spring Application context, one or more.  

1. What is web.xml

The /WEB-INF/web.xml file is used to define how to deploy the web module to a Servlet container like JBoss, Tomcat, Glassfish or any other servlet container. It’s defined by Sun since Java 1.4 ( or 1.2?  not  so sure) and part of the Java Servlet specification. The file name and locations can not be changed.

Basically web.xml tell container all servlets in the web application with <servlet> element , then tell container when to use which servlet by the url mapping  with <servlet-mapping> element.

Here is a reference of all elements in web.xml from Oracle WebLogic  document.

In Spring MVC project, for most cast, there is only one servlet org.springframework.web.servlet.DispatcherServlet. Let this DispatcherServlet handle all the requests. After container hands over the request to DispatcherServlet, the income http request formally enters the Spring world.  A controller will be chosen to handle the request according to @RequestMapping.

2. What is context configuration xml

In XML style configured Spring MVC project, there will be at least one xml to configure Spring MVC WebApplicatonContext. As Spring document says, there are 2 type of WebApplicationContext:

  • Root WebApplicationContext
  • Servlet WebApplicationContext

All servlets, althrough in most case only one DispatcherServlet, share root context. Each Servlet has its private context. Spring tries to locate a bean first in Servlet context, if not found, then search root context. A Spring MVC project can use both or just any one of them. In practical there really isn’t much difference between which context(s) is used.

The default configuration file for root WebApplicatonContext is /WEB-INF/applicationContext.xml

The default configuration file for servlet WebApplicatonContext is /WEB-INF/[servletName]-servlet.xml

The files’ name and location can be changed in web.xml.

3. More details with demo project

This is the directory hierarchy of the demo project.

image

It’s created in Eclipse as maven project with simple “maven-archetype-webapp” archetype.

image

In this demo, both root context and servlet private context are used just for demo. Service/Repository beans are registered in root context. Controller beans are registered in servlet private context. Define all beans in just one context is fine also.

The root context configuration file applicationContext.xml list below:

<?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:beans="http://www.springframework.org/schema/beans"
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">

<!-- register service/persistence beans in root context -->
<context:component-scan base-package="com.shengwang.demo.service" />

</beans>

The servlet private context configuration file dispatcher-servlet.xml list below:

<?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:beans="http://www.springframework.org/schema/beans"
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">

<!-- register controller in servlet private context -->
<context:component-scan base-package="com.shengwang.demo.controller"/>

</beans>
These 2 spring configuration are just for demo. In real use you need more configuration in them like persistence, security, etc.

The web.xml list below:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Demo for understanding web.xml of spring mvc project</display-name>

<!-- ===================================================== -->
<!-- 1. Create root context with spring listener -->
<!-- Remove this means only use servlet contxt -->
<!-- ===================================================== -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- ===================================================== -->
<!-- Can modify default root context config file -->
<!-- ===================================================== -->
<!--
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
-->


<!-- ===================================================== -->
<!-- 2. Define servlet with private context -->
<!-- ===================================================== -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- ================================================= -->
<!-- Set contextConfigLocation to empty -->
<!-- means only use root context -->
<!-- ================================================= -->
<!--
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
-->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- ===================================================== -->
<!-- One servlet, the dispatcher, to rule it all -->
<!-- ===================================================== -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>

The listener ContextLoaderListener is used to create root WebApplicationContext, <context-param>can be used to change config file location. 

<servlet> and <servlet-mapping>  work in pairs. The only servlet in this demo is named dispatcher, so the default servlet private context file is /WEB-INF/dispatcher-servlet.xml, it will handle all income request because its url-pattern is “/”, which means it’s the default servlet for all request not handled by other servlets. Since there is only one  servlet dispatcher, so in fact it will handle all requests.

Tuesday, July 21, 2015

Basic Configuration for logback

Here is the basic logback configuration for these goals:

  • One log file per day.
  • Keep max n days’ log. Over old log file will be automatically deleted (n=30  in this demo)
  • Max size of every log file x  (x=200MB in this demo)

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration>
  <configuration>
  <!-- define where to store the log file -->  
  <property name="LOG_HOME" value="." />  
    
  <!-- to screen --> 
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <!-- screen output pattern -->
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level [%F:%L] - %msg %n</pattern>
    </encoder>
  </appender>

  <!-- to file -->
  <appender name="FILE"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <!-- log file name -->
      <FileNamePattern>${LOG_HOME}/itf.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
      <timeBasedFileNamingAndTriggeringPolicy
        class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
        <!-- or whenever the file size reaches 200MB -->
        <maxFileSize>200MB</maxFileSize>
      </timeBasedFileNamingAndTriggeringPolicy>
      <!-- keep 30 days' worth of history -->
      <maxHistory>30</maxHistory>
    </rollingPolicy>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
      <!-- log file pattern:
        %d{...} : date and time in format
        %thread : thread name
        %-5level: log level, left aligned, 5 words length
        [%F:%L] : file name and line number
        %msg    :message
        %n      : newline -->
      <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level [%F:%L] - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="INFO">
    <appender-ref ref="STDOUT" />
    <appender-ref ref="FILE" />
  </root>
</configuration> 

put the logback.xml file in the resources folder. For example in a maven project, put logback.xml in src/main/resources/

Thursday, July 2, 2015

How to set development/test/production environment in spring project (Java Config)

In real life development, a project always need different sets of configurations for development, system test and production environments. Most common variables in these different environments are database location or jms location.

If the project uses spring and will not run in any container, the spring profiles can be used to make your life easier when switching environments. This article demonstrates the best practice to do so in my experiences to achieve these goals:

  1. Finally there will be only one packaged jar for all different environment
  2. The same jar can run in development environment, by giving option  "-Dspring.profiles.active=development" to JVM
  3. The same jar can run in test environment by giving option  "-Dspring.profiles.active=test" to JVM
  4. The same jar can run in production environment without options to JVM
  5. The JUnit test cases can easily switch between different environments

If your project will run within web containers, should use JNDI to define the resources and inject resources into Java code.

The basic idea is put property variables in 3 different property files, namely development.properties/test.properties/production.properties, then use the proper file for different environment ( spring active profile).

This tutorial uses spring Java config. For tutorial using spring XML config, see here.

In this demo, there are 2 beans, a data source which connecting to different DB, and a hello world print out different string in different environment.

0. What you need

  • JDK 1.7+
  • Maven 3.2+
  • Spring 4.1.0.RELEASE

1. Maven pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.shengwang.demo</groupId>
<artifactId>spring-use-profiles-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>spring-use-profiles-java</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>

<!-- Database -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>


<!-- Test Artifacts -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.0.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>

</dependencies>

<!-- Use Java 1.7 -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>



This dependencies in this demo can be divided into 3 groups, Spring, Database connection and Unit test.




2. Define Java class




There are 3 classes. The first one is a simple hello world bean, which use a property value to say hello to.

package com.shengwang.demo;

import org.springframework.stereotype.Component;

@Component
public class HelloWorldBean {
String name;

public HelloWorldBean(String name) {
this.name = name;
}

public String sayHello() {
return "Hello "+name;
}
}



The second class is the main class.

package com.shengwang.demo;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class DemoMain {

public static void main(String[] args) {
AnnotationConfigApplicationContext ctx= new AnnotationConfigApplicationContext(DemoJavaConfig.class);

HelloWorldBean helloWorld = ctx.getBean(HelloWorldBean.class);
System.out.println(helloWorld.sayHello());
}
}



The main class creates the spring context from a Java class called DemoJavaConfig, which is the spring configuration, then just use spring context to get a bean and call the method of the bean, here is the HellowWorldBean. The third class, DemoJavaConfig, is the key of this article.

package com.shengwang.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

@Configuration
public class DemoJavaConfig {

@Value("${hellow.world.name}") String helloWorldName;

@Bean
public HelloWorldBean helloWorldBean() {
return new HelloWorldBean(helloWorldName);
}

/**
* Add PropertySourcesPlaceholderConfigurer to make placeholder work.
* This method MUST be static
*/
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
Resource resource;
String activeProfile;

PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();

// get active profile
activeProfile = System.getProperty("spring.profiles.active");

// choose different property files for different active profile
if ("development".equals(activeProfile)) {
resource = new ClassPathResource("/META-INF/development.properties");
} else if ("test".equals(activeProfile)) {
resource = new ClassPathResource("/META-INF/test.properties");
} else {
resource = new ClassPathResource("/META-INF/production.properties");
}

// load the property file
propertySourcesPlaceholderConfigurer.setLocation(resource);

return propertySourcesPlaceholderConfigurer;
}
}



As a spring configuration class, class DemoJavaConfig has annotation @Configuraton. Inside the class definition, there is a field variable helloWorldName. Annotation @Value is used to get value from the property files. Then use it as constructor argument to init the HelloWorldBean. To make the property files work, a static bean must be added to return a PropertySourcesPlaceholderConfigurer. What's in the static method propertyConfigurer is create PropertySourcesPlaceholderConfigurer with only ONE property file, according to active profile to determine which property file will be used. There are 3 property files represents development/test/production environments respectively.




4. Property file




Property files are plain text files. Line starts with '#' is comment. There are 3 property files: development.properties, test.properties, production.properties.  Three files have same properties but with different values.  Only 2 are listed here to save space. development.properties:

# properties for development environment

# jdbc properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=simplePassword

# hello world property
hellow.world.name=development environment



production.properties:

# properties for production environment

# jdbc properties
jdbc.driver=oracle.jdbc.OracleDriver
jdbc.url=jdbc:oracle:thin:@192.168.203.95:1521:sip
jdbc.username=userABC
jdbc.password=complexPassword

# hello world property
hellow.world.name=production environment



Now the whole project directory hierarchy looks like.




image




5. Specify profile during development




As beginning mentions, in development, set JVM options -Dspring.profiles.active=development in your IDE or command line.  For example in Eclipse, this can be done using menu Run->Run Configuration. This JVM option only need to be specified for run the project. There is no need to specify this JVM option for JUNIT test.

image


Run the project and we can see it's running in the development environment.




image




6. Specify profile for Junit




On thing to notice is that the annotation @AcctiveProfiles does NOT work, we need to set the system property before spring context initialized.

package com.shengwang.demo;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = DemoJavaConfig.class)
//@ActiveProfiles("development") // Does NOT work
public class HelloWorldBeanTest {

@Autowired HelloWorldBean helloWorld;

public HelloWorldBeanTest () {
// set active profile manually in constructor
System.setProperty("spring.profiles.active","development");
}

@Test public void testSayHello() {
assertEquals("Hello development environment",helloWorld.sayHello());
}
}



Hope this article can make your life easier!

Powered by Blogger.

About The Author

My Photo
Has been a senior software developer, project manager for 10+ years. Dedicate himself to Alcatel-Lucent and China Telecom for delivering software solutions.

Pages

Unordered List