Spring

Spicy Spring : Scheduler does not shutdown

Posted on by  
Michel Breevoort

On my current project we use Java 8, Spring 4.3 and Tomcat 7.0 as application server. After the scheduling functionality was added to the project the application server did not shut down any more, it hung till the end of time. I like to use the default Java implementations when possible so the configured scheduler was the java.util.concurrent.ScheduledThreadPoolExecutor.

After some investigation we found out that the application server did not shutdown because the created ScheduledExecutorService bean did not stop. The threads in the thread pool didn’t stop when the application context is destroyed. The destroyMethod is defined and Spring calls the shutdown method but it still did not stop the application server. When I tested with Spring Boot it shuts down without a problem. Spring has also their own ThreadPoolTaskScheduler with much more configuration options. Strangely it does not implement the same interface java.util.concurrent.ScheduledExecutorService as I would expect from the Spring framework but you can use both implementations.

Continue reading →

Handling YAML format in your REST with Spring Boot

Posted on by  
Willem Cheizoo

In general a REST service serves JSON document formats. In Spring Boot it is even the standard without having to configure anything. Over HTTP we have the ability to send a Content-Type as header to instruct the server to return a certain document format (Mime type). Besides handling JSON, XML is another common document format. But what if we want to serve or read a YAML document format? This tutorial provides the required steps to be able to handle objects in YAML format. To be able to send a YAML Content-Type with the header, and to be able to serialize and deserialize with the existing ObjectMappers of Jackson. This tutorial will use Spring Boot, Jackson and a YAML dataformat extension library for Jackson.

First we need to add the YAML Jackson extension to our Gradle build file.

Continue reading →

Spicy Spring: Customize error JSON response with ErrorAttributes

Posted on by  
Willem Cheizoo

The default JSON error body of Spring Boot can be customized or extended by defining our own ErrorAttributes implementation. In Spring Boot we get an error response JSON format for free. Any thrown Exception is automatically translated to this JSON format and returned with a corresponding HTTP status.

As soon as we throw an Exception in a @RequestMapping annotated method of a @Controller, the thrown Exception is translated to a HTTP status and a JSON error body. The default JSON error body looks like:

Continue reading →

Spicy Spring: Write your own AutoConfiguration

Posted on by  
Willem Cheizoo

In Spring we use the @EnableAutoConfiguration each time when we use the @SpringBootApplication annotation. If we look at the @SpringBootApplication we can see that this automatically enables the @EnableAutoConfiguration. This last mentioned annotation triggers all the auto-configuration enabled configurations on the classpath. We can write an auto-configuration enabled @Configuration ourself in only two steps.

package com.jdriven.example;

import org.springframework.context.annotation.Configuration;

@Configuration
public class MyOwnAutoConfiguration {

    //You can define your own beans here and
    //further setup this Configuration as you normally would do

}

Continue reading →

Spicy Spring: Inject your custom method argument in Spring MVC using HandlerMethodArgumentResolver

Posted on by  
Willem Cheizoo

In Spring MVC we get some method argument types resolved by default and injected in Spring MVC controller methods. Some examples are Model, Locale and OutputStream. What if we want to inject a custom argument in Spring MVC controller methods? In this example we extract the X-Application-Version HTTP header from the request and inject that as a method argument called version. Our controller class will look like the following:

@RestController
public class MyController {

    @RequestMapping("/persons")
    //I want the version to be automatically injected
    public List getPersons(String version) {
        .....
        return someList;
    }
} 

Continue reading →

Use Spring classpath Resource as Tuckey UrlRewriteFilter configuration

Posted on by  
Willem Cheizoo

Recently I wanted to use the Tuckey UrlRewriteFilter. It is described as: A Java Web Filter for any compliant web application server, which allows you to rewrite URLs before they get to your code.

I wanted to load my urlrewrite.xml as a Spring (classpath) resource, instead of loading it from the default location provided by the UrlRewriteFilter. The default behavior loads the configuration file from /WEB-INF/ulrewrite.xml. In my case I wanted to load it from the /src/main/resources folder, which is the root of my classpath.

Continue reading →

Spicy Spring : Different ways of Autowiring

Posted on by  
Willem Cheizoo

I would like to show different ways of using Spring's @Autowired annotation: Constructor, Method and Field autowiring.
The examples I show are all a form of byType autowiring mode (constructor autowiring mode is Analogous to byType). Take a look at the Spring Reference guide for more information on the Autowiring modes.

Create a constructor with a dependent bean as constructor parameter and add the @Autowired annotation to the constructor. A big advantage of autowiring by constructor is that the field can be made final, and therefore may not be changed after construction.

Continue reading →

Using Spring managed Bean in non-managed object

Posted on by  
Willem Cheizoo

We have to deal with legacy code, even when we would like to use the best and newest technologies available. Imagine the new code is written with the newest technologies of the Spring Framework and the legacy code is not written in Spring at all. Then using Spring managed Beans in non-managed Spring objects is one of the patterns we have to deal with. The legacy code has non-managed Spring objects, while the code we want to reference to is a Spring managed Bean. How do we solve this problem?

Let's assume we have a managed Spring Bean called TaxService and an object called LegacyObject. The LegacyObject is the legacy code from where we would make a reference to the method calculateTax on the managed Spring Bean.

Continue reading →

Introduction to Spring profiles

Posted on by  
Michel Meeuwissen

So many men, so many minds. When we are implementing software for different customers we sometimes need to handle various requirements for the same project. For example Customer A needs SAML authentication and customer B needs LDAP authentication. With Spring Profiles (available from Spring 3.1) we are able to provide a way to segregate parts of our implemented application configuration. This blog will help us to make certain code or rather certain Spring beans only available for specific requirements. For example the example used in this blog can be used to activate the required authentication provider for the provider manager when using Spring Security. Profiles can be configured by annotations and/or by xml. Annotations @Component or @Configuration annotated beans can contain the annotation @Profile to only load them in a certain environment.

@Component
@Profile("ldap")
public class LDAPAuthentication {
   public LDAPAuthentication() {
      System.out.println("LDAP Authentication set by annotations");
   }
}

@Component
@Profile("saml")
public class SAMLAuthentication {
   public SAMLAuthentication() {
      System.out.println("SAML Authentication set by annotations");
   }
}

Continue reading →

Auto inject dependencies in JUnit using Mockito

Posted on by  
Sjoerd Schunselaar

While writing unit tests, you often have to mock dependencies like services or controllers. Often  a constructor is used to autowire the dependencies as shown in the example below. In the Test class I instantiated the ContactService using a contactRepository Mock object

@Service
public class ContactServiceImpl implements ContactService {

private final ContactRepository contactRepository;

    @Autowired
    public ContactServiceImpl(final ContactRepository contactRepository) {
    this.contactRepository = contactRepository;
    }

    public void saveContact(final Contact contact) {
    contactRepository.save(contact);
    }
}

Continue reading →

shadow-left