Using Java 8 Optional to set Current User ModelAttribute in Spring Security

This post will be a bit of a follow on from that last one which discussed using a User entity from a database in Spring Security Authentication Object, so it’s probably worth reading that first.

The new Optional  class in Java 8 lets us create a neat little mechanism for transferring our User entity, if one exists, into every controller method, using a ControllerAdvice  along the way.

Starting with the UserPrincipal  class from the last post we’ll make the following modification:

Continue reading “Using Java 8 Optional to set Current User ModelAttribute in Spring Security”

How to use a custom UserDetailsService to save a DB User Entity in the Spring Security Authentication Object

When working with web applications most of the time we’ll want to store our User objects in a Database and use something like JPA annotations and spring data repositories to make life easier with our persistence.

Unfortunately Spring Security assumes it’s own User class which doesn’t necessarily have all the fields we might be interested in assigning to a User, such as email.

However, it is possible to marry your DB User Entity with your Spring Security User object so that it is available from Authentication objects.

Continue reading “How to use a custom UserDetailsService to save a DB User Entity in the Spring Security Authentication Object”

Introducing $ – the Java Static Constructor

So this one will probably be controversial.

I’ve been playing around with this idea for a while, really since I started using Ruby in a hobby capacity.  When instantiating a variable in Ruby, let’s say a simple 2D point class, you would use the following syntax:

Whereas we all know that the equivalent Java instantiation would be

There’s something I like about that static style constructor in Ruby, especially when constructing a method argument.

Continue reading “Introducing $ – the Java Static Constructor”

Fluent Setters

What are Fluent Setters?

Lately I’ve been making all my setters in bean classes fluent, meaning they return this object and can be chained together.

Take the following bean which exposes a lot of fields.

In order to use this class with it’s default constructor we have to initialize it and then can call all the setters on the object.

Continue reading “Fluent Setters”