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 →
In Java 8 we can create a constructor reference. We must use the syntax Class::new
and we get a constructor reference. This syntax is not supported in Groovy, but we can use the method pointer or reference syntax .&
to turn a method into a closure. We can even turn a constructor into a closure and use it everywhere where closures are allowed.
In the following sample code we have a User
class with some properties. Via the User.metaClass
we can get a reference to the method invokeConstructor
and turn it into a method closure:
Continue reading →
Suppose I want to make coffee. This involves 4 steps:
- 1a. grind coffee beans
- 1b. heat water
- combine
- filter
Continue reading →
Building a rest API with akka and spray is easy. This is how I did it: SprayApiApp:
import akka.actor.{ActorSystem, Props}
import akka.io.IO
import akka.pattern.ask
import akka.util.Timeout
import spray.can.Http
import scala.concurrent.duration._
object SprayApiApp extends App {
//we need an ActorSystem to host our application in
implicit val system = ActorSystem("SprayApiApp")
//create apiActor
val apiActor = system.actorOf(Props[ApiActor], "apiActor")
//timeout needs to be set as an implicit val for the ask method (?)
implicit val timeout = Timeout(5.seconds)
//start a new HTTP server on port 8080 with apiActor as the handler
IO(Http) ? Http.Bind(apiActor, interface = "localhost", port = 8080)
}
ApiActor:
import akka.actor.{ActorLogging, Actor}
import spray.http.MediaTypes
import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol
import spray.routing._
object RobotProtocol extends DefaultJsonProtocol {
//Our domain class
case class Robot(name: String)
//We use the default json marshalling for Robot.
//There are multiple jsonFormat methods in DefaultJsonProtocol. Depending on how many parameters the model class has.
//Robot has just one, so we use jsonFormat1
implicit val RobotFormat = jsonFormat1(Robot)
}
import RobotProtocol._
class ApiActor extends Actor with HttpService with ActorLogging {
//A list of our domain objects
var robots = List(Robot("R2D2"), Robot("Asimo"))
//The HttpService trait defines only one abstract member, which
//connects the services environment to the enclosing actor or test
def actorRefFactory = context
//This actor only runs our route, but you could add
//other things here, like request stream processing or timeout handling
def receive = runRoute(apiRoute)
//Notice that both path methods return a Route. We need to chain them together with ~
val apiRoute: Route =
path("robots") {
get { //with get we will return our current list of robots
log.info("Building get route")
complete {
log.info("Executing get route")
//complete will return the result in an appropriate format
//With SprayJsonSupport it knows how to marshall a List to json
//With RobotFormat it knows how to marshall Robot
robots
}
} ~ post { //With post we will add a robot
log.info("Building post route")
handleWith { robot: Robot => //handleWith will unmarshall the input
log.info("Executing post route")
robots = robot :: robots
robot //handleWith will also marshall the result. Here we simply return the new robot.
}
}
} ~ path("") { //When we go to localhost:8080/ just show a link to localhost:8080/robots
respondWithMediaType(MediaTypes.`text/html`) { //XML is marshalled to `text/xml` by default, so we simply override here
complete {
[The list of robots](/robots)
}
}
}
}
Continue reading →
As shown in a the post Nifty JUnit : Working with temporary files, it is possible to use @Rule
in a JUnit test, which is a Method level Rule. In this example I would like to show the variation of the @ClassRule
for a Class level Rule.
The @Rule
is fired before each test method (just like @Before
) and after each test method (just like @After
) of the test class, as shown in the example below.
Continue reading →
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 →
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 →
I get this question quite often and I struggled with it many times before: How do I work with temporary files in my JUnit testcases? I would like to explain two simple ways of working with temporary files in JUnit.
Create a temporary file with the Java File API and mark it directly as deleteOnExit()
. The created file will be deleted when the JVM exits.
Continue reading →
Grails has some useful tags for rendering errors of an object in a view. Below we see an example whichs renders the errors for a single bean.
<g:hasErrors bean="${person}">
<g:renderErrors bean="${person}"/>
</g:hasErrors>
Continue reading →
We are building a Spring Boot application with a REST interface and at some point we wanted to test our REST interface, and if possible, integrate this testing with our regular unit tests. One way of doing this, would be to @Autowire
our REST controllers and call our endpoints using that. However, this won't give full converage, since it will skip things like JSON deserialisation and global exception handling. So the ideal situation for us would be to start our application when the unit test start, and close it again, after the last unit test. It just so happens that Spring Boot does this all for us with one annotation: @IntegrationTest
. Here is an example implementation of an abstract class you can use for your unit-tests which will automatically start the application prior to starting your unit tests, caching it, and close it again at the end.
package demo;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
// Your spring configuration class containing the @EnableAutoConfiguration
// annotation
@SpringApplicationConfiguration(classes = Application.class)
// Makes sure the application starts at a random free port, caches it throughout
// all unit tests, and closes it again at the end.
@IntegrationTest("server.port:0")
@WebAppConfiguration
public abstract class AbstractIntegrationTest {
// Will contain the random free port number
@Value("${local.server.port}")
private int port;
/**
* Returns the base url for your rest interface
*
* @return
*/
private String getBaseUrl() {
return "http://localhost:" + port;
}
// Some convenience methods to help you interact with your rest interface
/**
* @param requestMappingUrl
* should be exactly the same as defined in your RequestMapping
* value attribute (including the parameters in {})
* RequestMapping(value = yourRestUrl)
* @param serviceReturnTypeClass
* should be the the return type of the service
* @param parametersInOrderOfAppearance
* should be the parameters of the requestMappingUrl ({}) in
* order of appearance
* @return the result of the service, or null on error
*/
protected T getEntity(final String requestMappingUrl, final Class serviceReturnTypeClass, final Object... parametersInOrderOfAppearance) {
// Make a rest template do do the service call
final TestRestTemplate restTemplate = new TestRestTemplate();
// Add correct headers, none for this example
final HttpEntity requestEntity = new HttpEntity(new HttpHeaders());
try {
// Do a call the the url
final ResponseEntity entity = restTemplate.exchange(getBaseUrl() + requestMappingUrl, HttpMethod.GET, requestEntity, serviceReturnTypeClass,
parametersInOrderOfAppearance);
// Return result
return entity.getBody();
} catch (final Exception ex) {
// Handle exceptions
}
return null;
}
/**
* @param requestMappingUrl
* should be exactly the same as defined in your RequestMapping
* value attribute (including the parameters in {})
* RequestMapping(value = yourRestUrl)
* @param serviceListReturnTypeClass
* should be the the generic type of the list the service
* returns, eg: List * @param parametersInOrderOfAppearance
* should be the parameters of the requestMappingUrl ({}) in
* order of appearance
* @return the result of the service, or null on error
*/
protected List getList(final String requestMappingUrl, final Class serviceListReturnTypeClass, final Object... parametersInOrderOfAppearance) {
final ObjectMapper mapper = new ObjectMapper();
final TestRestTemplate restTemplate = new TestRestTemplate();
final HttpEntity requestEntity = new HttpEntity(new HttpHeaders());
try {
// Retrieve list
final ResponseEntity entity = restTemplate.exchange(getBaseUrl() + requestMappingUrl, HttpMethod.GET, requestEntity, List.class, parametersInOrderOfAppearance);
final List> entries = entity.getBody();
final List returnList = new ArrayList();
for (final Map entry : entries) {
// Fill return list with converted objects
returnList.add(mapper.convertValue(entry, serviceListReturnTypeClass));
}
return returnList;
} catch (final Exception ex) {
// Handle exceptions
}
return null;
}
/**
*
* @param requestMappingUrl
* should be exactly the same as defined in your RequestMapping
* value attribute (including the parameters in {})
* RequestMapping(value = yourRestUrl)
* @param serviceReturnTypeClass
* should be the the return type of the service
* @param objectToPost
* Object that will be posted to the url
* @return
*/
protected T postEntity(final String requestMappingUrl, final Class serviceReturnTypeClass, final Object objectToPost) {
final TestRestTemplate restTemplate = new TestRestTemplate();
final ObjectMapper mapper = new ObjectMapper();
try {
final HttpEntity requestEntity = new HttpEntity(mapper.writeValueAsString(objectToPost));
final ResponseEntity entity = restTemplate.postForEntity(getBaseUrl() + requestMappingUrl, requestEntity, serviceReturnTypeClass);
return entity.getBody();
} catch (final Exception ex) {
// Handle exceptions
}
return null;
}
}
Continue reading →
We currently use Vert.x in several internal and external projects. Until the most recent project we where building our Vert.x modules using Maven. Gradle is our build tool of choice, but the default approach described at the Vert.x site caused several issues:
- The task of cloning, cleaning and configuring the template project is error-prone;
- The template project does not support recent Gradle versions >= 2.x;
- This approach is not compatible with the Gradle support in IntelliJ IDEA.
Continue reading →
Defining a maven plugin on a submodule in a multi-module maven project can give us a 'No plugin found' error. Especially if we have a multi-module project and we want to apply a maven plugin in only one specific module this error occur pretty often. Let's say we have a multi-module root pom which looks like this.
4.0.0
com.jdriven.blog
maven-plugin-multimodule
0.1-SNAPSHOT
pom
module1
module2
Continue reading →