Spring is a powerful framework — and not only for dependency injection. It can strongly benefit applications as a whole. Sometimes, you need to create your own highly customized stand-alone application instead using an out-of-the-box Spring Boot solution.

Typical cases are custom utility applications used for one-time jobs like email scraping for needed information or custom database migration.

In those cases, you could use Spring Batch, but sometimes, if it is a one-time job, it is easier to just write own code.

You do not need to resign from using Spring in that case — just add it as a stand-alone context and use your favorite Spring features.

Context Loading in Stand-Alone Apps: The Most Critical Feature

AnnotationConfigApplicationContext is the most important class for loading Spring beans in stand-alone applications. It allows annotated classes as inputs, including component package scans and @Configutration -marked classes. In fact, this is the core of every stand-alone Spring application.
Typically, using AnnotationConfigApplicationContext looks like:

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

Where AppConfig.class is a separate @Configuration class with all needed beans.
In less complicated cases application main class could be also configuration, then code look like following
ComponentScan(basePackages = "YOUR_COMPONENTS_PACKAGE")
public class ApplicationX { private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationX .class); private SomeService someService;

@Autowired public ApplicationX(SomeService someService) { this. someService = someService; } public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationX.class); ApplicationX appx = context.getBean(ApplicationX .class); appx.start(); } private void start() { LOGGER.info(„ApplicationX started.”); // do stuff } }
The constructor of the AnnotationConfigApplicationContext class takes multiple arguments of the @Configuration class. That means all configuration could be passed at once during the creation of the context. That functionality enables adding separate configurations for separate components like databases or custom security features.

Configuration Classes: What They Are

All classes annotated by @Configuration in Spring are considered as configuration classes, but what does this really mean?
According to the Javadoc, the annotation @Configuraion indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.
So it is like a factory class to produce some beans declared in it.
The simplest example of a @Configuration class looks like the following:
public class ConnectionConfig {

@Bean public MyConnectionService myConnection() { // some stuff }


Adding a Spring context to a stand-alone application is not difficult, and having it can significantly benefit applications. There is nothing wrong with using your own customized applications for one-time jobs, and Spring has special features to help with dependency injection in stand-alone applications.
By the techniques presented in this article, a developer can add their own Spring beans and inject them where needed — or add whole components like Spring Data to a stand-alone application.

Useful resources

  • https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html
  • https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/AnnotationConfigApplicationContext.html


Modern applications need to follow security rules. Time when limited or zero attacks on applications are gone, now each developer need to protect own app.
One of the good way to establish good level of application is keeping dependencies up to date.
There is really good Gradle plug-in that help with that task – owsap dependency check.

To add it just include in project build.gradle file following snippet

 classpath "org.owasp:dependency-check-gradle:3.0.2"

in buildscript dependencies section
apply plugin: "org.owasp.dependencycheck" 

in applay plugin section of your file.

Next using command

gradle dependencyCheckAnalyze -info

You will get detailed information about project dependencies that have vulnerabilities.



Many times, we encounter the need to store date and time in our database. Throughout application development, we need to make CRUD operations on that stored data. In my case, I use Spring Boot with Spring Data as a persistence layer. I’m still not sure whether the word “layer” is truly appropriate in modern development techniques, but nevertheless, we’ll say that Spring Data is my persistence layer.
As database I use Postgres which has quite nice features and what is most important it’s free.
Detailed technology stack looks like:
- PostgreSQL DB
- Spring Boot 1.5.3
- Spring Data JPA
- Lombok (since I do not like to write getters, setters and so on)
- Angular 2 on front end (but that is not important in this post)


The first problem that I encounter is JPA mapping types in my database. I have a Timestamp column type, which fits all my needs at the database level — it stores date and time with the appropriate time zones, so everything that I need is right there.
But, JPA (the Hibernate implementation in our case) implements a Postgres SQL timestamp as java.sql.Timestamp or java.sql.Date which is not what I want in my Spring Boot application. I mean, I could deal with ava.sql.* types but as of Java 8 we have LocalDate and LocalDateTime classes with that nice new features like plusDays methods.
Generally I would like to have new Time API in my application.
So this is what our database table looks like:
CREATE TABLE public.tableA (
	id int4 NOT NULL DEFAULT nextval('terminykursow_seq'::regclass),
	termA timestamp NULL,
	termB timestamp NULL,
	idother int4 NULL

And this is the corresponding entity:
@Table(name = „tableA”, schema = „public”)
public class EntityA implements Serializable { @Id @SequenceGenerator(name=„tableA_seq”, sequenceName=„tableA_seq”, allocationSize=1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator=„tableA_seq”) private Integer id; private LocalDateTime terminod; private LocalDateTime termindo;

… other entity stuff … }


Without any changes, the code compiles and the application starts correctly… but there are several errors, like:
“2017-08-08 18:32:06.911 ERROR 28428 --- [nio-8472-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: ERROR: operator does not exist: timestamp without time zone > bytea”

The error does not tell exactly what the problem is, which is, in my opinion, the weakest characteristic of Spring Boot and Spring Data JPA logging. Nevertheless, I decided to add some converters as described in the JPA documentation.
Tip no 1: Always use appropriate documentation.

Please note that Converter is class that implements
interface and You do not need any annotation on that class.
So my implementation looks like this:
import javax.persistence.AttributeConverter;
import java.sql.Timestamp;
import java.time.LocalDateTime;

public class LocalDateTimeConverter implements AttributeConverter { @Override public Timestamp convertToDatabaseColumn(LocalDateTime attribute) { return attribute != null ? Timestamp.valueOf(attribute) : null; }

@Override public LocalDateTime convertToEntityAttribute(Timestamp dbData) { return dbData != null ? dbData.toLocalDateTime() : null; } }

At this point, all I need to add is an annotation to my Entity fields that drives to the Converter class:
Convert(converter = LocalDateTimeConverter.class)

The final Entity looks like this:
@Table(name = „tableA”, schema = „public”)
public class EntityA implements Serializable {
    @SequenceGenerator(name=„tableA_seq”, sequenceName=„tableA_seq”, allocationSize=1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator=„tableA_seq”)
    private Integer id;
    @Convert(converter = LocalDateTimeConverter.class)
    private LocalDateTime terminod;
    @Convert(converter = LocalDateTimeConverter.class)    
    private LocalDateTime termindo;

    … other entity stuff …

And BOOM :) everything work as expected.


There are many good mechanisms in Java 8 that You can use in Your Spring Data application, one of my favorite is Time API and with Converter mechanism You are no longer sentenced to javax.sql.* classes.


What is JMS? Java Message Service could be considered as high level framework that communicates two or more clients each other by sending messages. JMS is fully supported by Java EE and has been specified in JSR -914 (see links section).
Base operations that we could done via JMS are:
- send messages
- receive messages
Typically one JMS client create message and send it to the server (JMS message broker) and other JMS client receive it and perform some operation. Of course this is high level overview and lower process is more complicated while added i.e. security and so on.

Where we use it? Well we could use JMS everywhere where we need increase scalability, integrate different environments, batch processing support, asynchronous communication without time pressure.
Common use is email sending process where one client create message that templates email should be send to appropriate receiver/s and send message to message broker where it is queued and receivers can download them when connected.

What are the key players on the JMS market? Below You could find my private favorite JMS vendors list:
- Amazon SQS
- ActiveMQ
- Oracle Weblogic
- HornetQ (perv. JBoss messaging) see link no 2

What is activemq? ActiveMQ is implementation of Message Oriented Middleware which is used to communicate ie via JMS clients. As we could read at official page (see link no 3) it is open source system that is fast, supports cross language clients and protocols and what’s the most important supporting fully JMS 1.1 specification.
Latest version is 5.x.x and this version will be used in demo.

Active mq server From the download section of official ActiveMQ page (see link no 3) You can download latest server binary package. After un-zip it took almost 100MB of disk space.
Unzipped binaries is all You need to start Your server.
At my windows machine starting script is located at: apache-activemq-5.x.x\bin. I use activemq.bat but there ale similar scripts for Linux too.
Bat script setup local env and finally run jar file called activemq.jar which is located at bin folder.

After run in command line starting script and successfully started server You should see something similar to:

Now You could type http://localhost:8161/admin/ to access Your ActiveMQ server administration console, note that default login and password is admin.

It should look like that:

Now You could add Your first queue in Queues menu.

ActiveMQ client example I created sample client for ActiveMQ server in Java 8 using threads and lambdas. Whole code You could find at my github: https://github.com/tjancz/jms-activemq-example.git

Below You could see sender code:

and the receiver code:

If You would like to see all working stuff just form my github repo.
There is also great documentation on ActiveMQ page.

Summary JMS is not scary as it looks and ActiveMQ is great MOM that could easily help You set up message queues and integrate different systems in MQ way.

1. https://jcp.org/aboutJava/communityprocess/final/jsr914/index.html
2. http://hornetq.jboss.org/
3. http://activemq.apache.org/