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)


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

  <!-- to file -->
  <appender name="FILE"
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <!-- log file name -->
        <!-- or whenever the file size reaches 200MB -->
      <!-- keep 30 days' worth of history -->
    <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>

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

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" 




<!-- Spring -->

<!-- Database -->


<!-- Test Artifacts -->


<!-- Use Java 1.7 -->

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;

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);

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;

public class DemoJavaConfig {

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

public HelloWorldBean helloWorldBean() {
return new HelloWorldBean(helloWorldName);

* Add PropertySourcesPlaceholderConfigurer to make placeholder work.
* This method MUST be static
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

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

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


# properties for production environment

# jdbc properties

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

Now the whole project directory hierarchy looks like.


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.


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


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;

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

@Autowired HelloWorldBean helloWorld;

public HelloWorldBeanTest () {
// set active profile manually in constructor

@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.


Unordered List