Feed aggregator

An Introduction to the Java Collections Framework

Javalobby Syndicated Feed - Mon, 11-Apr-16 03:02

This article is part of Marcus Biel’s free Java course focusing on clean code principles. In this piece, you will be given a high-level introduction of the Java Collections Framework (JCF). Collection is a word with several overloaded meanings, unfortunately. To clear things up, we will first discuss the word’s meanings upfront.

A video of this article is also available here.

Categories: Java

Quick Access to Eclipse IDE Features

Javalobby Syndicated Feed - Mon, 11-Apr-16 02:31

As Lars points out on the ide-dev mailing list, a lot of Eclipse IDE users aren’t aware of some very handy features, especially the one-feature-to-rule-them-all: Quick Access.

In an Eclipse IDE, Quick Access will take you quickly to the feature you need. To activate Quick Access, type Ctrl+3 and start typing (or click in the entry field in the toolbar and start typing).

Categories: Java

Currying Functions in Scala

Javalobby Syndicated Feed - Mon, 11-Apr-16 00:31

For a long time I couldn’t understand currying functions in Scala and how they work. That was really horrible! Occasionally I met the currying functions in the code and wasted too much time on reading them. So finally I decided to learn how they work and where they could be applied.

Let’s start from a definition. A currying function is a function which could accept a fewer number of parameters than are declared, then it returns a function with unused parameters. This definition is totally weird. In order to understand it we need to go through several examples. And be sure that you already know how simple Scala functions work.

Categories: Java

In Love with Ada

codecentric Blog - Sun, 10-Apr-16 22:17

Anyone out there remembering the Ada programming language? In this blog post, I’m going to give you a short introduction to Ada, the history of its name and some of the current occurrences in pop culture.

Hello World in Ada

To compile our first Ada program we need to install the GNAT – the GNU compiler for Ada. On Ubuntu this can be done with

sudo apt-get install gnat-4.8

On other OS, you may have to use other package managers.

Our hello world program hello.adb

with Ada.Text_IO; 
use Ada.Text_IO;
procedure Hello is
  Put_Line ("Hello, world!");
end Hello;

… can be compiled and linked with

$ gnatmake hello.adb
gcc-4.8 -c hello.adb
gnatbind -x hello.ali
gnatlink hello.ali

This will result in an executable hello in the same directory. Running it will finally print out the desired message:

Hello, world!

As you can see, Ada looks a little bit like Pascal and is indeed based on it. The full syntax can be found in the lastest reference manual. Some of the main features are exceptions and built-in concurreny handling. The IDE for Ada development is GPS – the GNAT Programming Studio.

A brief history of Ada

The Ada programming language was built in the late 1970s by the US DoD (Department of Defense) in order to consolidate the huge amont of different programming languages used there. It is named after Augusta Ada King, Countess of Lovelace, better knows as Ada Lovelace, an English mathematician from the 19th century. This woman is said to be the first programmer ever, or at least she worked on an algorithm for Babbage’s analytic engine, some kind of mechanical device for performing simple (from our point of view) computations. Her achievements made her an iconic person and the name Ada has several occurrences in modern culture.

Ada in Pop Culture

The godfathers of cyperpunk, William Gibson and Bruce Sterling, picked up the topic in their novel The Difference Engine which more or less etashblised a whole new genre called steampunk. Of course, Ada does appear in that story.

Being a big fan of Lego, I really like this to-be set: Lovelace & Babbage.

Lego set Lovelace + Babbage

It features two minifigures Ada Lovelace and Charles Babbage and of course the analytical machine which is designed to house a small computer like a Raspberry Pi. Please help to make this set real and vote for it!

The name Ada often occurs in computer games. The last recent occurrences I know of are in Ingress and Fallout 4.

ADA Refactor - a weapon in Ingress Ingress is an augmented reality game played on mobile devices. Two factions battle against each other for so-called portals, locations inside the real world. You can capture enemy portals be attacking them. The ADA Refactor is one of the most powerful weapons.

The RPG Fallout 4 is set in a post-apocalyptic world where the player wanders the wasteland and fights for survival. There is a modifiable robot companion called Ada. My version looks like this:

Ada - a Fallout 4 robot companion

There’s another robot called Lady Lovelace. Both are clear references to the real-world Ada.

If you are aware of any further recent Ada occurrences, please let me know.

The post In Love with Ada appeared first on codecentric Blog.

Categories: Agile, Java, TDD & BDD

Java 8 – Default Methods in Interfaces

Javalobby Syndicated Feed - Sun, 10-Apr-16 21:31

In this article we will explore the Java 8 default methods feature in interfaces. The Java 8 says “Default methods enable new functionality to be added to the interfaces in libraries and ensure binary compatibility with code written for older versions of those interfaces”.

As Java evolved over the years, the interfaces introduced in the Java library require adding new functionality. If you add new methods in the interface without having default methods feature, all the classes which already implemented the interfaces should undergo for a change. This results in changing thousands of lines of code. To avoid this, the Java 8 introduced default method feature. That is, if you want to add any functionality to the existing interface, you can add it by using default method feature without affecting the implementations.

Categories: Java

Upcoming classes

Dan North's Blog - Sun, 10-Apr-16 10:47

I am excited to announce some public dates for my Testing Faster and Software Faster classes. These include the first 2-day classes this year, and the first ever public dates for London.

Software Faster masterclass

Software Faster is for people looking beyond Scrum and the other agile methods that have been around since the mid–1990s. These methods can shrink delivery times from years to months, but then what? You want to deliver in weeks, days or even hours. The last two decades have seen amazing technological advances, in languages, tools, techniques, and in the availability of inexpensive, on-demand infrastructure. What use is a two-week planning horizon if you can build, deploy, test and discard several product ideas in a single morning?

In the masterclass I customise the Software Faster content to the people in the room. One group may go deep into technical topics like adaptive architecture and emergent design, deployment and automation, or wrangling legacy systems. A different group may concentrate on delivery challenges like estimation, planning and scheduling, or team dynamics and organisation design, or metrics and lean operations. It’s never the same class twice, which is why I enjoy teaching it so much.

I will be running the 2-day class in Copenhagen next week (there may still be a couple of seats left), and in London on 6–7 June.

I am running 1-day workshops in association with these conferences:
Budapestat Craft conference on 27 April (sold out)
– Manchester Agile Manchester conference on 10 May
Edinburgh at XP 2016 on 24 May
Amsterdam at GOTO Amsterdam on 13 June

Testing Faster masterclass

Testing Faster is a brand new class for anybody working in an agile team, not just for testers. I designed the class for teams who are struggling to understand where testing fits into agile software delivery, and how to transition their traditional testers and testing practises. The agile testing world seems to be stuck in unhelpful dichotomies of “automated vs. manual testing” or “testing vs. checking”. My experience is that testing is a richer, broader and deeper set of disciplines than these distinctions would suggest.

The Testing Faster class starts by exploring the purpose of testing, and gets into test strategy, i.e. what, where and when to test, and test design, or how to test. Then we look at the relationship between BDD and testing, and at the pros and cons of automation. Finally we turn the subject on its head and think about what it means to design for testability. What is testable architecture and design? What about testable deployment or testable runtime?

I am running the 2-day masterclass in London on 2–3 June. The 1-day workshop in Budapest on 26 April has already sold out.

I will update my blog as we schedule new classes. Depending on demand that may happen more regularly!

Filed under: none

Patterns, 20 Years Later: The Constructor Function Explained

Javalobby Syndicated Feed - Sun, 10-Apr-16 02:31
tl;dr Patterns, 20 Years Later: A Constructor Function is a function designed specifically to construct instances of entities (typically objects, although in languages which do not support objects as native types, this will typically be something that masquerades as an object). It is often seen as a variation on a Factory Method, though there is enough variation on the intent that it is worth calling this out as a standalone pattern.


We want to define an easy interface for creating an object, but defer the actual decision of what object type to instantiate. (In this respect, it is very very similar to Factory Methods and the main decision point on which to use will vary on the context.)


A class can’t anticipate the class of objects it must create. In other words, either the system is deliberately designed to be “open,” allowing types that weren’t known at the time of the framework’s creation to be created (which is the case in most application frameworks, for example), or the system is deliberately drawing an encapsulatory barrier between the class representing the abstract type and the implementations, in order to help facilitate better decoupling. Most systems or platforms that support some notion of “plugins” are in the former category, although often at a binary level of interoperability, rather than a source-language level of interop. (Most Component Object Model (COM) developers will remember CoCreateInstance, for example, which is the classic example of a Factory Method.)

Categories: Java

Introduction to Java 8 Streams

Javalobby Syndicated Feed - Sat, 09-Apr-16 23:01

In Java 8, we have a new feature called “Streams.” These “Streams” are similar to collections, but there are some differences. Primarily the collections are the data structures which will hold the data. To process the data, we need to get the data from the collections and execute some logic. For example, we have a list of students. We need to sort the students based on the marks secured, in descending order. To perform the above-said logic, we have to follow these steps.

Create a Comparator

package org.smarttechie;

import java.util.Comparator;

public class MarksComparator implements Comparator<Student>{

public int compare(Student student1, Student student2) {

   if (student1.getTotalMarks() > student2.getTotalMarks()) {
       return -11;
    } else if (student1.getTotalMarks() < student2.getTotalMarks()) {
      return 1;
    } else {
      return 0;

Call the Method

 Collections.sort(students, new MarksComparator());

With Streams we can do this in a simple way. The code snippet is given below.

Categories: Java

Detecting Java Race Conditions With Tests, Part 1: Lost Updates

Javalobby Syndicated Feed - Sat, 09-Apr-16 02:31

Detecting Java race conditions is hard; detecting them during tests is impossible. Really?

In the following article, I want to show you that it is actually rather easy. In Part I of this article, you will see how to detect lost updates, the first type of Java race conditions. In Part II, we will look at the second type of Java race conditions: non-atomic access.

Categories: Java

Spring Batch FlatFileItemWriter Hacking

Javalobby Syndicated Feed - Fri, 08-Apr-16 21:31

In this article I explained how to use FlatFileItemWriter class to write a flat file without using a complete Spring batch flow.

Person.java domain object

package com.flatfile.domain;

public class Person {

   private final String firstName;
   private final String lastName;
   private final String middleName;

   public Person(String fn,String ln,String mn){
   public String getFirstName() {
      return firstName;

   public String getLastName() {
      return lastName;

   public String getMiddleName() {
      return middleName;

   public String toString() {
      return firstName+"&amp;#9;"+lastName+"&amp;#9;"+middleName;



This is a builder pattern for constructing a Person object:

Categories: Java

What Agile Software Development has in common with Sailing

codecentric Blog - Fri, 08-Apr-16 08:04

Writing about Agile feels a bit like shoveling water from a strainer to the ocean … with a spoon. But as this blog post says “Sailing” in its headline it fits quite nicely with the ocean metaphor.

I like sailing! And I like Agile Software Development (well, most of the time)! So what could suggest itself more than comparing what both have in common. This way this hopefully is a – different kind of – refresher on some of the key concepts of Agile Software Development. At the same time you might also learn something about sailing. Or at least you can watch some of the cool embedded sailing clips.

When talking about sailing here it is about sailing competitive in a regatta. So it looks something like this which might also come close to some projects when looking at the weather conditions ;-).

Inspect and Adapt

Sailing fast is the embodiment of inspect and adapt. You are constantly checking the position of the sails and your current course in comparison to the wind and the competition. This is especially important when you are on the beat towards the windward mark.

In Agile this part is covered by the retrospectives that are held after each sprint. Even though most (agile) teams will – at some point of time – start to improve also outside the retrospectives (implicitly by doing small inspect and adapt cycles at the coffee kitchen). Of course these things must be in balance with the sprint goals. Some improvements can simply not be done at any time, but require some planning.

The goal is to constantly improve technically and methodically to become faster and/or deliver better quality or to improve in other areas that are important to the project at that time. As the focus of projects might change the focus in retrospectives might need to change as well.

In sailing it is quite obvious that you cannot change the wind, but you can adjust a lot of other factors by steering and trimming the boat. Keep this in mind for retrospectives as well and try to focus on the things you can change as a team and not at those that are out of your reach.

For retrospectives it is especially important to keep focus. Keep focus on the past sprint because that is what we are normally looking at. Keep focus on things the team can improve and not something in cloud-cuckoo-land the team can anyway not influence. Do not try to derive as many actions as possible, but just a few concrete ones. Then really work on those in the next sprint and do some kind of follow-up.

Another real-life problem is that retrospectives – and this is also true for other “standard”-meetings – tend to get boring after some point of time. Here is an important difference to most sailing regattas. Software projects often last quite long. One thing that can help here is to have really great variations in the retrospectives. A good source to get new ideas for retrospectives is for example the Retromat. Other possibilities are rotating the facilitator. A team member or a scrum master from another team can for example facilitate retrospectives every now and then. Reflect on the way the team is doing retrospectives. Invite stakeholders or members from other teams you are collaborating with. Change the location and as a last resort: Bring some cake :-).

Team and Communication

Sailing is a team effort and so is (agile) software development. First of all it is for sure important to understand (and accept) strength and also potential weaknesses of the team members. And as with a sailing crew the mutual understanding will naturally grow the longer a team stays together. For sure this is not only true for software teams. But here is also a major difference between a regatta crew and a software development team. In sailing there is one person – the skipper – who has full responsibility what is happening and into which direction the boat is heading. In an agile team the responsibility is shared. But this means really everyone has responsibility and not that noone has ;-).

volvooceanraceImage from https://3d-car-shows.com/volvo-ocean-race-2014-sets-sail-in-october

On the communication side there is sometimes a slight tendency in agile development processes to overextend. Some readers might object here, but from my experience more communication does not necessarily mean better nor clearer communication. On a sailing boat there are clear commands and those are communicated so that everyone understands what happens next, e.g. preparing to tack. Of course the bigger complexity makes clear communication a lot harder in software projects. And on a sailing boat there is also no room for discussions. Something that is for sure important in software projects as long as they do not run out of the rudder.

Try to utilize the existing meetings to its full extend before inventing new ones. For example the daily standup in Scrum. This is for sure a good opportunity to transport a good amount of important information. But too often these standup meetings are getting painfully boring and inefficient. Stay focused and potentially make this a topic in the next retrospective. Small teams sitting together in one office anyway might not need those meetings on a daily basis. Do not stick to the book if it does not fit your needs!

Skills and Equipment

On a sailing boat you have different positions like the helmsman (typically the skipper), the main trimmer, the jib trimmers (port and starboard), a bowman, a tactician and potentially more depending on the size of the boat.

Now in agile teams we also have different “positions” like frontend expert, backend hacker, database guru, the masterchief tester and potentially a scrum master (sorry, I ran out of cool terms). And likewise a sailing crew, members of an agile team can switch positions to some extend. But there simply is a certain degree of expert knowledge that can hardly be avoided.

The challenge of mapping stories to be done during a sprint to the skills available in that sprint could probably fill a blog post of its own. The basic assumption should always be that the team has all skills required in the project. But still vacations and focus on certain types of stories might lead to a mismatch here. Just keep that in mind and try to plan early on for this.

Of course in longer running projects it is essential to spread the knowledge required for the different areas … even if that might mean writing some documentation or slowing down development in some sprints. This will help a lot in later sprints where more team members have the required skills to work on different kind of tasks. At least on a basic level. If for example the helmsman/skipper of a regatta yacht is going over board for sure the rest of the crew is still able to pick him up again. Even though maybe not that fast and elegant as the skipper could do it himself. But hopefully the point gets clear.

Anyway communicating these kind of things to the stakeholders is really a key factor. For example planning a lot of pairing on a certain topic in one sprint to spread certain knowledge. This way it gets clearer why there might be a short drop in the velocity and the decision can be taken together on what might be good sprints to do this.

If you look at nothing else in the above video than 2:30 to 2:40. That is some skill in a quite stressful situation getting the shackle attached in time before the sail goes up. If that fails for sure it would mean disaster strikes.

The above clip shows some nice skills and team work, thus it could have been added also to the previous section. Working on ones skills for sure is equally important in sailing and (agile) software development. For sure this happens a lot already while working on the project (sailing), but sometimes you need to train some special maneuvers. And it is important to have the time for that outside of the daily project work.

On the equipment side things are easy: You just want to get the best equipment possible :-). For sponsored regatta teams money might be less of a problem here than in some software projects. But just keep in mind that working around for example missing hardware or missing permissions is probably more expensive in the end.


Sure this is a blog post with a wink :-). And a lot of things sound very obvious while writing and proof reading it, but in the daily project routine one is easily moved away from these things. Maybe you just want to do a comparison – just for you – with your favorite sports or hobby. It might help getting a fresh view on some aspects in agile software development.

For the end just one of my favourite sailing clips. It is just too funny when the sailing guys are talking about the Kite guy asking “Is the Kite guy any good, does he know the rules of sailing?” … “He’s gonna smoke all of us!”.

Seems they just get a fresh point of view from sailing together with different boat classes … and a Kite guy :-).

The post What Agile Software Development has in common with Sailing appeared first on codecentric Blog.

Categories: Agile, Java, TDD & BDD

JavaFX Tips to Save Memory: Shadow Fields for Properties and Observables

Javalobby Syndicated Feed - Fri, 08-Apr-16 04:31

In the world of JavaFX, the Properties API allows UI developers to bind values to UI controls. This capability is surprisingly easy; however, when object models use properties too often, an application can quickly run out of memory. I usually will write two separate objects such as a POJO class and a presentation model object. This technique is often used in Swing-based applications. From a JavaFX perspective, you could just create one object with properties to allow observers (listeners) to update values. This sounds fine, right? Not exactly, because the main issue is when all of the object’s (POJO) attributes (fields) are properties that also wrap actual values, the programmer (user of the API) may not want to bind or use properties at all, but only want to access the actual values. So, what is a JavaFX developer to do?

I often go to the blog Pixel Perfect by Dirk Lemmermann, who will often post very useful JavaFX tips. Recently, Dirk blogged about how to save memory using an interesting pattern called Shadow Fields.  To see his post, please visit his blog entry JavaFX Tip 23: Save Memory! Shadow Fields for Properties. Dirk’s JavaFX tip does help solve the problem mentioned above (lessening the heap); however, I noticed boilerplate code that has to exist to provide (a smart determination) to the caller of whether the return is the actual object or the property wrapper object. For example, instead of returning an IntegerProperty object when calling get or set methods, the code will return an int or Integer value, thus saving memory. Furthermore, the code declares two variables to hold one of the two value types. For example:

Categories: Java

Avoid Working With Classes and Reflection Where Possible

Javalobby Syndicated Feed - Fri, 08-Apr-16 04:01

As with all my posts, there are exceptions and caveats. But in your general code the only time you should be dealing with MyClass.class is when initialising your logger:

Logger logger = LoggerFactory.getLogger(HelloWorld.class);

In day to day code you should have no other reason to be handling raw class files. It’s anti-object orientation and it’s often difficult to understand for someone reading the code.

Categories: Java

Reclaiming Design Patterns (20 Years Later)

Javalobby Syndicated Feed - Fri, 08-Apr-16 02:31
20 years ago, the "Gang of Four" published the seminal work on design patterns. Written to the languages of its time (C++ and Smalltalk), and written using the design philosophies of the time (stressing inheritance, for example), it nevertheless spawned a huge "movement" within the industry. Which, as history has shown us, was already the hallmark of its doom—anything that has ever become a "movement" within this industry eventually disappoints and is burned at the public-relations stake when it fails to deliver on the overhyped promises that it never actually made. It’s time to go back, re-examine the 23 patterns (and, possibly, a few variants) with a fresh set of eyes, match them up against languages which have had 20 years to mature, and see what emerges. (Spoiler alert: all of the original 23 hold up pretty well, and there’s a lot of nuance that I think we missed the first time around.)

Patterns: What were they for, exactly?

In the early days of the patterns "movement," when the patterns were new and fresh, we didn’t spend much time really discussing this all that much. They just were; those of us who read the book nodded at a few of them, having experienced them before in code "in the wild,” and we went on about our day. Intuitively, it seemed, we realized that there were places where we could apply this knowledge, we appreciated the new dimensions the patterns opened inside our heads, and… yeah, cool.

The Gang of Four (GOF) seemed to realize from the beginning that this was a subtle art/science; in the last chapter of the book (which nobody ever seemed to read, unfortunately), they said:

Categories: Java

Java 8: Base64 Encoding & Decoding [snippet]

Javalobby Syndicated Feed - Thu, 07-Apr-16 23:01

The Base64 encoding and decoding is a long overdue JDK API feature. As part of Java 8 the Base64 encoding and decoding feature came into the Java standard library. Earlier we were using private and unsupported sun.misc.BASE64Encoder and sun.misc.BASE64Decoder classes which are not part of the standard API. In Java 8, we got the java.util.Base64 class to perform Base64 encoding and decoding. The sample code on Base64 usage is given below.

package org.smarttechie;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

public class Base64Sample {
public static void main(String args[]){

String str = "Welcome to see java.util.Base64";
Base64.Encoder base64Encoder= Base64.getEncoder();

//encoding byte array into base 64
byte[] byteArray = null;
try {
    byteArray = base64Encoder.encode(str.getBytes("UTF-8"));
    System.out.println("Base64 Encoded String : " + new String(byteArray,"UTF-8"));

    //decoding byte array into base64
    Base64.Decoder base64Decoder= Base64.getDecoder();
    byte[] strdec=base64Decoder.decode(byteArray);

   System.out.println("Base64 Decoded String : " + new String(strdec,"UTF-8"));
  } catch (UnsupportedEncodingException e) {

Categories: Java

Java 8 — Functional Interfaces (SAM)

Javalobby Syndicated Feed - Thu, 07-Apr-16 04:01

There are numerous interfaces in the Java library that declare a single abstract method; few such interfaces include:

// in java.lang package
interface Runnable { void run(); }

// in java.util package
interface Comparator<T> { boolean compare(T x, T y); }

// java.awt.event package:
interface ActionListener { void actionPerformed(ActionEvent e); }

// java.io package
interface FileFilter { boolean accept(File pathName); }

Java 8 has introduced the concept of “functional interfaces” that formalizes this idea. A functional interface specifies only one abstract method. Since functional interfaces specify only one abstract method, they are sometimes known as Single Abstract Method (SAM) types or interfaces.

Categories: Java

Binding Configuration to JavaBeans in Spring Boot

codecentric Blog - Thu, 07-Apr-16 03:00

It is quite easy to assign external configuration values to variables in Spring. The @Value annotation has been available in the Spring Framework for a long time now. With the introduction of @ConfigurationProperties in Spring Boot, a new way for binding configuration values to JavaBeans has been introduced. Depending on how configuration data is passed to an application, there are slight differences in how configuration is bound to JavaBeans. I have been very confused about this recently, so I’m going explain said differences in this blog post.

Reading Configuration from different sources

There are many ways to specify configuration data in Spring Boot and the framework defines a order for overriding configuration values from different sources. This way we can, for example, use profiles to define different environments for an application (like local, dev, qa and prod). Another option is to put local configuration into the application.properties file and provide configuration for the different environments via environment variables. Specifying configuration via environment variables is the recommended way for scalable applications according to the 12 factor method. For this reason I’m going to show how environment variables override configuration data from the application.properties file.
In the remainder of this blog post, I’m going to use a small example project to analyse the binding of configuration data. I’m assuming that you’re familiar with Spring Boot in general and the @Value and @ConfigurationProperties annotations.

The spring-boot-configuration-example project

There are differences in the way Spring binds configuration from environment variables and from property files to JavaBeans. Furthermore the result of the binding depends on whether you use the @Value annotation or @ConfigurationProperties. To demonstrate this differences, I have created the example project codecentric/spring-boot-configuration-example. The project allows you to try this for yourself and to play around with different settings.

The project provides two configuration classes for reading configuration data: AnnotationConfiguration, which uses the @Value annotation and TypeSafeConfiguration, which uses the @ConfigurationProperties annotation. AnnotationConfiguration is defined with the following Spring Expression Language (SpEL) expressions to read configuration data:

public class AnnotationConfiguration {
    @Value("${example.property-name:not set}")
    public String propertyDashName;
    @Value("${example.property.name:not set}")
    public String propertyPointName;
    @Value("${example.propertyName:not set}")
    public String propertyName;
    @Value("${example.propertyname:not set}")
    public String propertyname;
    @Value("${example.property_name:not set}")
    public String property_name;

TypeSafeConfiguration on the other hand uses the configuration prefix “example” and has the following fields:

@ConfigurationProperties(prefix = "example")
public class TypeSafeConfiguration {
    private String propertyName;
    private String propertyname;
    private String property_name;

Note that we can not implement an equivalent for example.property-name and example.property.name in TypeSafeConfiguration, since neither is a valid field name in Java. If you want to inspect how Spring binds configuration values to this classes all you need to do is execute the run.sh script (hope you’re using Unix/Linux). It will print out what it is doing and how the configuration affects the state of the application. The following steps are executed in order:

  1. Run the application without any configuration.
  2. Run the application with environment variables set.
  3. Run the application with application.properties.
  4. Run the application with both, environment variables and application.properties.

When running with environment variables (Step 2 and 4), the script will set the following environment variables:


Note the missing underscore in the second case. It will be interesting to so, how Spring maps this to our configuration classes. For example I can not tell which of the SpEL expressions in AnnotationConfiguration will get the value of EXAMPLE_PROPERTYNAME. When the run script executes the application with a properties file, the script will write the following to src/main/resources/application.properties:


The mapping between properties and SpEL expressions is pretty obvious, since there is a one to one mapping for each SpEL expression. However I have no idea which values will get bound to TypeSafeConfiguration. So let’s run this and have a look at it! You can run it yourself like this:

git clone https://github.com/codecentric/spring-boot-configuration-example
cd spring-boot-configuration-example

In the remainder of this blog post, I’m going through the output of run.sh. If you are interested in the details, I have created this gist containing the output. Not surprisingly, all fields will be unset, when running the application without configuration.

Reading Configuration from environment variables

Running the example with just environment variables set is a bit more interesting. The log shows the following bindings for TypeSafeConfiguration (I’m using colors to make it easier to spot the differences):

Field name Configuration value
property_name null

… and for the SpEL expressions in AnnotationConfiguration:

SpEL expression Configuration value
example.property-name not set
example.property.name EXAMPLE_PROPERTY_NAME
example.propertyName EXAMPLE_PROPERTYNAME
example.propertyname EXAMPLE_PROPERTYNAME
example.property_name EXAMPLE_PROPERTY_NAME

Looking at the first table we can see that the TypeSafeConfiguration.propertyName is set to the value of EXAMPLE_PROPERTY_NAME, while TypeSafeConfiguration.propertyname is set to the value of EXAMPLE_PROPERTY_NAME. TypeSafeConfiguration.property_name can not be set by environment variables. The results for AnnotationConfiguration can be seen in the second table: example.property.name and example.property_name both get the value of EXAMPLE_PROPERTY_NAME, while example.propertyName and example.propertyname get the value of EXAMPLE_PROPERTYNAME. The SpEL expression example.property-name can not be set by environment variables.

What is interesting about this? Looking only at the results for TypeSafeConfiguration, I would expect that the environment variable EXAMPLE_PROPERTY_NAME gets mapped to TypeSafeConfiguration.property_name. But instead the value of EXAMPLE_PROPERTYNAME is used. This feels especially confusing to me, when comparing it with the second table. Here the SpEL expression example.property_name will get the value of EXAMPLE_PROPERTY_NAME!

Another inconsistency is the handling of TypeSafeConfiguration.propertyName and TypeSafeConfiguration.propertyname compared to the handling of the SpEL expressions example.propertyName and example.propertyname. TypeSafeConfiguration.propertyName gets the value of EXAMPLE_PROPERTY_NAME while TypeSafeConfiguration.propertyname gets the value of EXAMPLE_PROPERTYNAME, but both SpEL expressions get the value of EXAMPLE_PROPERTYNAME.

The last observation we can make is, that it is not possible to set SpEL expressions containing dashes via environment variables. This is particulary cumbersome since the recommended way for specifying keys in property files, according to the Spring Boot documentation, is to use dashes (see Table 24.1 in the Spring Boot documentation). Imaging a team building all of it’s configuration based on dash-separated keys in properties files, only to notice that they cannot set these values using environment variables, when deploying to production.

Reading Configuration from a properties file

The next part of the run.log shows how configuration from an application.properties file will be mapped to our configuration beans. Here’s a summary of the output for TypeSafeConfiguration:

Field name Configuration value
propertyName example.propertyName
propertyname example.propertyname
property_name example.property-name

… and for AnnotationConfiguration:

SpEL expression Configuration value
example.property-name example.property-name
example.property.name example.property.name
example.propertyName example.propertyName
example.propertyname example.propertyname
example.property_name example.property_name

The data in AnnotationConfiguration is exactly what we expected, so no need to talk about that. What’s really weird is that TypeSafeConfiguration.property_name it set to the value of example.property-name and not example.property_name. I have no idea why it behaves this way. Furthermore we can see, that it is possible to set all values, which was not possible when using only environment variables.

Mixing configuration from environment variables with configuration from properties files

The last thing to have a look at, is how configuration is overridden when providing both, application.properties and envrionment variables. Again here is the result for TypeSafeConfiguration:

Field name Configuration value
property_name example.property-name

… and for AnnotationConfiguration:

SpEL expression Configuration value
example.property-name example.property-name
example.property.name EXAMPLE_PROPERTY_NAME
example.propertyName EXAMPLE_PROPERTYNAME
example.propertyname EXAMPLE_PROPERTYNAME
example.property_name EXAMPLE_PROPERTY_NAME

Since environment variables have precedence over configuration from application.properties, everything that can be initialized from environment variables will be. Only TypeSafeConfiguration.property_name and the SpEL expression example.property-name will be set to the respective value from application.properties.


There two ways to bind configuration data to JavaBean in Spring Boot: by using type safe binding, via @ConfigurationProperties and by using SpEL expressions via @Value. Convenient as it may be, the results can be confusing depending on whether configuration is set from environment variables or properties files. As a take away, my recommendations are:

  • Be consistent with: don’t mix camel case, snake case, and the like when defining properties.
  • Don’t use dashes in property keys.
  • Don’t use underscores in field names.

This will save you a lot of headaches when working with configuration values in Spring Boot.

The post Binding Configuration to JavaBeans in Spring Boot appeared first on codecentric Blog.

Categories: Agile, Java, TDD & BDD

Put Your Java 8 Method References to Work

Javalobby Syndicated Feed - Thu, 07-Apr-16 02:31

Method References

As we all know by now, we can use Method References, like String::isEmpty, in Java 8 to reference a method that is being used when we, for example, stream over elements. Take a look at this code snippet:

    Stream.of("A", "", "B").filter(Stream::isEmpty).count();

which will produce the result 1 (because there is just one empty element in the stream). But, if we want to filter out non-empty strings, we need to write .filter(s -> !s.isEmpty()) which is a Lambda. Clearly, there is an annoying asymmetry here. We can use a method reference, but not its negation. We can write predicate.negate() but we cannot write Stream::isEmpty.negate() or !Stream::isEmpty.

Categories: Java

Apping It Up With Dashboards and Gadgets

Javalobby Syndicated Feed - Thu, 07-Apr-16 00:31

In this series of posts I am covering some of the many ways you can benefit from XpoLog and especially on how to get the most valuable information about your log4j event logs.

By running Analytic Search on your log4j data, you can among other things measure your application performance and thread activity, measure code activity with class and method analytics on log4j, build various reports and analysis, and make use of various visualization gadgets for maximum analysis.

Categories: Java

Java Quiz: Extending an Abstract Class

Javalobby Syndicated Feed - Wed, 06-Apr-16 21:31

Last week's quiz asked you what happens when you try to compile the following program:

class Outer {
    private int a = 12;
    private int b = 6;
    Outer() {
        NestedA nestedA = new NestedA(4);
        a = a -12;
    class NestedA {
        NestedA(int y){
            NestedB nestedB = new NestedB(y);
            nestedB.methodB(y, a);
            a= a + b - y;
        private void methodA(int z) {
        class NestedB {
            NestedB(int i) {
                a = a - i; b = b +i;
            private void methodB(int x, int z) {
                if(x < 5) {
                    a = a+x+b;
                b = b+z; 
    public static void main(String[] args) {
        NestedA nestedA = new Outer().new NestedA(2);

Over 1,800 of you responded, and if you're one of the 24.3% that got it right, then you know the answer is that the program writes "-a22-b18-a44-b42" to the standard output.

Categories: Java

Thread Slivers eBook at Amazon

Syndicate content