Getting Started with Spring (via Spring Boot)

How do I get started with Spring?

Software developers often ask me what the easiest way to get started with Spring is. There are, of course, multiple options for getting started. This post lays out a simple yet effective way to get started with Spring.

One of the best things to happen to Spring is a project called ‘Spring Boot’. In my opinion, this is the quickest and easiest way to get started with a Spring project.

Spring Boot

Spring Boot is a project from Pivotal Software that is designed to get you up and running fast. As the project website states, “Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can ‘just run’. We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.”

Spring Initializr

What’s even more exciting about Spring Boot is the Spring Initializr site at start.spring.io This site will generate a Spring Boot project skeleton (choose either Gradle or Maven), let you set project metadata as well as which dependencies or Spring Boot Starters you want to include in your project. You then click the ‘Generate Project’ button to download a zip archive of your skeleton project. How cool is that??

There’s also a ‘full version’ from the same start.spring.io page if you want to choose options like Java Version, Language, and specific Spring Boot Starter dependencies.

OK, what’s the first step?

To get started, head over to start.spring.io From there, choose ‘Gradle Project’ and ‘Spring Boot 1.4.0’:

Spring Boot with Gradle

Or, if you’d prefer, you can get this project directly from my github repository – simply visit my Spring Beginner Tutorial repo where you can clone or download this Spring Boot project.

Specify Project Metadata:

Project Metadata

Under dependencies, just leave this blank for now.

Click Generate Project and download a zip of your project skeleton. Extract this into your project workspace and head over to Eclipse.

Generate Project

Open your project in Eclipse

From the Eclipse menu, choose File > Import > Gradle Project > Next

Specify the root directory of your project. Eclipse will then import your project.

Running a Spring Boot application

Now let’s go ahead and run our newly created Spring Boot application. Right-click on the project and choose ‘Debug As’ > ‘Java Application’. If, at this point, you get a dialog asking ‘Select Java Application’, go ahead and choose ‘ProjectNameApplication’, where ProjectName is the name you gave your project. Usually it’s the top option in the list.

In the console output, you’ll see several lines printed out. Once you see a line like the one below printed out, you know that your Spring Boot project is up and running:

INFO 10076 --- [ main] c.d.s.SpringBootIntroApplication : Started SpringBootIntroApplication in 2.833 seconds (JVM running for 3.426)

What does this project actually do?

If you followed my instructions exactly, you ended up with the basics of a Spring project, with a few essentials. Take a look at the debug output, in particular the following lines:

INFO 10076 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
INFO 10076 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
INFO 10076 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.4
INFO 10076 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
INFO 10076 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)

As you can see, the following gets launched as a part of running our Spring Boot application:

  1. Tomcat
  2. Spring WebApplicationContext

I’ll get into more details around the different context options in later blog posts. For now, just know that the Spring WebApplicationContext, along with the Tomcat Servlet Engine, are what allows your application to accept web requests. With your project still running, open up a web browser to http://localhost:8080 and see what response you get. You should see something similar to the following:

404

Don’t be alarmed with the 404 response, it’s actually expected. The 404 is actually coming from your Spring Boot application. A 404 is being returned because we still have more work to do. We need to map URLs to methods in our Spring Boot application to handle the request that come to the application. In future blog posts, I’ll get into those details.

Congratulations!

Good job! You’ve now created your first Spring (via Spring Boot) application! It’s a simple application, but has all the pieces necessary for a Spring project. Spring Boot helped us along the way; it’s a great way to get a Spring project up and running.

Spring Beginner Tutorial: Dependency Injection Part 3 – DI without Spring

What is Dependency Injection? – Part 3

This is the third in a series of blog posts that I’m putting together for developers who are beginning to work with Spring. This post attempts to describe the basics of what dependency injection is.

Dependency injection is a fundamental part of Spring. It is so core to Spring that it warrants some explanation.

In the past couple of posts including this one I haven’t even shown a single line of ‘Spring’ code. Dependency injection, by itself, does not require Spring. In fact, there are many frameworks (outside and within Java) that use Dependency Injection. This is because DI is a design pattern. It’s a way to structure your code and manage your dependencies. It helps you control how classes interact with (and depend on) each other, both in production code as well as and especially in your test code.

Let’s start of with an example. You can follow along on my Spring Beginner Tutorial on github.

In the example below, ‘ExampleRunner’ depends on ‘InterfaceDependency’:

How does interfaceDependency get instantiated and set on ExampleRunner?

The simplest way that it could get instantiated and set is via the constructor of ExampleRunner. We could ‘new’ it up in the constructor of ExampleRunner, like so:

But this creates a problem. ExampleRunner is now coupled to a concrete implementation, InterfaceDependencyImpl, which is a concrete class (i.e. not an interface). This is a problem because every place ExampleRunner is used, it is always going to use InterfaceDependencyImpl. They are coupled together, inseparable, and there’s nothing a client of ExampleRunner can do about that.

Testing concerns

One place where coupling becomes a problem is when we want to unit test ExampleRunner. What if, for example, InterfaceDependencyImpl made a network call, or talked to a database, or performed some other long running operation. Now, anytime we run our unit tests against ExampleRunner we must wait for the network call to return (long and brittle), or depend on a database server to be running (unneeded dependency), or wait for some other process to finish. This is not good.

Dependency Injection to the rescue!

We can solve this problem with Dependency Injection (DI for short). DI follows the dependency inversion principle, which states:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend on details. Details should depend on abstractions.

In our example above, ExampleRunner needs remove its dependency on InterfaceDependencyImpl. But how to we do that?

We do that by introducing the idea of an Injector.

An Injector is an object that coordinates dependencies. To keep things simple, the Injector in this example is the main method. Its job is to instantiate and set, or ‘inject’ dependencies.

Types of Injection

There are two different ways that dependencies are injected: Constructor Injection and Setter Injection.

Constructor Injection

The first method of injecting dependencies that I’ll describe is Constructor Injection. Take a look at the example below. This is code that exists in the Injector (main method in this example):

Here, we instantiate InterfaceDependencyImpl. We then pass it in as a constructor argument to ExampleRunner. The passing in as an argument to the constructor is the ‘injection’ part. This is Constructor Injection since the point we are injecting it into is the constructor.

If you run this code, you’ll see the following printed out:

Setter Injection

Setter injection is done via a method, typically a setter method. In the example below, InterfaceDependencyImpl is passed into ExampleRunner via the setDependency method. You may have noticed that I don’t pass in any arguments to the constructor in this example — the dependency gets set via the setter:

Constructor injection and Setter injection are the most common ways to inject dependencies. I personally prefer constructor injection for all dependencies, as I prefer to have all my dependencies in place before a class is used. For me, I like knowing that the class has everything it needs before it’s used. However, there are cases where setter injection is appropriate. For example, sometimes you can avoid circular dependencies if you set the problematic property via setter injection (though you should avoid circular dependencies where possible anyway). In my current project, I can’t think of a single place where we use setter injection, and it’s a good-sized project.

What were you saying about testing?

Back to the testing discussion. If you remember, I stated that when two classes are too tightly coupled, testing becomes more difficult (and sometimes impossible). Being able to specify the dependencies of a class helps in this regard. For example, if I am writing tests for ExampleRunner, and I need to simulate specific behavior of InterfaceDependencyImpl (for example, throw an exception), it becomes problematic if ExampleRunner itself instantiates InterfaceDependencyImpl. It’s a problem because ExampleRunner nor my unit test can control whether InterfaceDependencyImpl throws an exception or not. There’s no reliable way to simulate that. If ExampleRunner controls the instantiation and setting of this dependency, I have no choice but to test with that implementation. However, if I use DI to set my dependencies, I do have control of the dependencies of the class I’m testing. So, if I wanted to simulate an exception, I can create a test class InterfaceDependencyWithExceptionImpl, which throws an exception when invoked. I then inject this implementation for the interfaceDependency property (via either Setter or Constructor injection, it doesn’t matter). My test code can then focus on the behavior of the unit under test (ExampleRunner in this case), and how it reacts to scenarios like a dependency throwing an exception. This way I can set up my tests in a way that simulates a wider variety of scenarios.

Conclusion

Dependency Injection is fundamental to understand when learning Spring. Furthermore, it promotes good design by encouraging components to be loosely coupled. DI promotes separating the creation of a class’s dependencies from the behavior of those classes, and opens up numerous testing scenarios. In these examples I purposely left Spring out, as my intention here is to show you simple examples of Dependency Injection so that you’re not bogged down with syntax and Spring-specific details.

Spring Beginner Tutorial: Dependency Injection Part 2 – What is a Dependency?

What is Dependency Injection? — Part 2

This is the second in a series of blog posts that I’m putting together for developers who are beginning to work with Spring. This post attempts to describe the fundamentals of what a dependency is.

In order to understand Dependency Injection (sometimes people call it Inversion of Control), we need to understand what dependencies are. Take a look at the Java code below. You can find the full example at my Spring Beginner Tutorial github repo.

I’ve tried to give the simplest example I could think of. In this example we have three classes, ExampleRunner, ClassDependency, and InterfaceDependency. We’ll get into the differences below. ExampleRunner depends on both ClassDependency and InterfaceDependency. In the run method of the ExampleRunner class above, we instantiate both ClassDependency and InterfaceDependency, and then call methods on both of these classes.

What does it mean when we say one class depends on another class?

The reason is simple. We say that one class depends on another because one class needs to call methods (or get information from, etc) on the class it depends on. In order for it to complete its job, it needs or depends on the other class. Without that class, it can’t carry out the work that it expects to do.

What is coupling?

Often, you’ll hear the term ‘coupling’ used in discussions of class dependencies. When one class uses another, we say that they are ‘coupled’. In other words, where you have dependencies, you have coupling, at least in a very basic form.

Types of Dependencies

Since I’ve now covered the basics, let’s dive into the different types of dependencies.

  • Class dependencies
  • Interface dependencies
  • Method dependencies
  • Field dependencies
  • Dependency in method

Class dependencies

Class dependencies are when one class depends on another class. In the example above, ExampleRunner depends on ClassDependency. ClassDependency is a concrete type — i.e. it’s not an interface.

Interface dependencies

ExampleRunner also depends on InterfaceDependency, which, as its name implies, is an interface dependency. InterfaceDependency is an interface. In this example, there is a somewhat hidden dependency in that since we instantiate InterfaceDependencyImpl, ExampleRunner also depends on this class. Later in the tutorial, we’ll get into how Spring helps us remove that dependency, but for now the thing to focus on is that InterfaceDependency is an interface, and the ExampleRunner class calls methods on it through this interface.

Field dependencies

In the example above, ExampleRunner also depends on a field. In this case it’s a field called ‘getField()’ (great name, I know :)). This is called a field dependency in that one class (ExampleRunner in our case) depends on the field of another (getField() on the ClassDependency class). This is what we’ll call a ‘field dependency’.

Dependency in method

Take a look at the dependencyInMethod method. Here, we again depend on ClassDependency. It’s just that, this time, the dependency is contained in a method, not as a field to the ExampleRunner class.

Import statements

One way to get a feel for the interface or class dependencies a given class has is to look at its import statements. Here you can find the packages or classes that contain the classes that the class you are examining uses. There’s a drawback to this, however, in that you won’t be able to see at a glance which classes the given class uses if those classes exist in the same package (since you don’t need to import classes that exist in the same package as the current class).

Conclusion

In this tutorial I describe what a dependency is, and give examples of the different types of dependencies. Understanding this is fundamental for understanding DependencyInjection and Spring.

Spring Beginner Tutorial: Dependency Injection Part 1 – ExampleRunner

What is Dependency Injection? – Part 1

This is the first in a series of blog posts that I’m putting together for developers who are beginning to work with Spring. This post sets us up to understand a basic principle of Spring – Dependency Injection.

To start us off, I’ve created a simple class with a main method. As you can see in the snippet below, all the main method does is instantiate an ExampleRunner class and call the run() method on it. This is what we’ll use to kick off the examples that follow.

Find the snippet below. You can see the full version of this example at my Spring Beginner Tutorial github repo:

In my next post we’ll dig into the fundamentals of Dependency Injection. Sometimes people call it Inversion of Control.

Conclusion

This is the introductory blog post that sets us up for the rest of the tutorial. It describes a simple class that allows us to execute code where we can view the examples that follow.

I hope you’ll follow along and find the tutorial helpful. I’ve been doing Spring for several years now, and I’ve felt that a simple tutorial for beginners is more than overdue. As always, send me your feedback and comments.

Sucking less every sprint

After battling the feature for about a week, he could see the light at the end of the tunnel.  His comment to me was, “man, looking back I could have gotten this completed so much faster if I knew what I know now.”

Earlier this month we hired a recent C.S. graduate.  He had been working as an intern for several months, and with the transition to full-time he let me know that he wanted to take on a bigger task.  The timing was right and I assigned him a simple yet slightly more involved task than he was accustomed to, and he went to work.

During our morning standups each day he would indicated progress — and it truly was progress — but the final solution kept eluding him.  After four days he said during standup, “today is the day I will complete this feature.”  But it didn’t get done.  It took him an additional three days.

I don’t fault him at all for taking the amount of time that he did on this feature.  It was more difficult than he was used to, and he wanted to make sure he nailed it.  In the end, he did a great job.

What struck me was his statement about how quickly he could have completed the task had he known what he knew after he was done.  It seems obvious, doesn’t it?  In a way it’s part of becoming self-aware:

Self awareness
Self-awareness

OK, maybe not self-awareness. Maybe it’s closer to self-reflection. This helps us suck less every year:

I’ve often thought that sucking less every year is how humble programmers improve. You should be unhappy with code you wrote a year ago. If you aren’t, that means either A) you haven’t learned anything in a year, B) your code can’t be improved, or C) you never revisit old code. All of these are the kiss of death for software developers.

I’d go as far as to say that you should suck less every sprint. If you’re not self-aware, if you’re not continually self-reflecting — you are dying as a programmer. If your team slogs through sprint after sprint, release after release, without any time to reflect on recent work, and how it could have been improved, it slow its progress to a halt. Or at least lose momentum. Which may turn you into a zombie.

How to Start a Django REST Framework project

Lately I’ve been working with Django REST framework.  Here are some notes to get you started:

1. Create a folder for your project:

2. Create a virtualenv to isolate dependencies, and activate it:

3. Install Django and Django REST framework:

4. ‘Start’ (create) your new project:

5. ‘Start’ (create) your initial app:

6. Sync your database:

7. Create a superuser:

That’s it!  Now you can launch your project by invoking the runserver command:

Pull up http://127.0.0.1:8000/ in a browser window to see your project running from your local box.

Bash: create alias

If you find yourself repeatedly running a wordy command, having to look up how to run a command, or forgetting a username and password combination, I suggest looking into creating a bash alias.

To create a bash alias, do the following:

1. Start up terminal

2. Type cd ~  to go to your home folder

3. Type touch .bash_profile to create the new file

4. Type vim .bash_profile or open this file in your favorite editor.

5. Add your alias by adding a line to this file in the format alias <alias name>='<command>’ . For example alias gw=’./gradlew’.  This will create an alias named gw , which when typed will run the command ./gradlew  from wherever gw  is typed.

6. Type . .bash_profile  to reload your bash profile which loads any newly added aliases.

At this point you can type your alias instead of the wordy command you had been previously typing.

java.net.BindException: Address already in use:8080

Address already in use, BindException

If you’ve ever encountered this exception:
java.net.BindException: Address already in use:8080
there’s a great tool that you can use to determine what application(s) are running on a specific port: lsof

Looking at the man page for lsof, we find the following:


DESCRIPTION
Lsof revision 4.81 lists on its standard output file information about files opened by processes for the following UNIX dialects:

AIX 5.3
FreeBSD 4.9 for x86-based systems
FreeBSD 7.0 and 8.0 for AMD64-based systems
Linux 2.1.72 and above for x86-based systems
Solaris 9 and 10

(See the DISTRIBUTION section of this manual page for information on how to obtain the latest lsof revision.)

An open file may be a regular file, a directory, a block special file, a character special file, an executing text reference, a library, a stream or a network file (Internet socket, NFS file or UNIX domain socket.) A specific file or all the files in a file system may be selected by path.

Instead of a formatted display, lsof will produce output that can be parsed by other programs. See the -F, option description, and the OUT-PUT FOR OTHER PROGRAMS section for more information.

In addition to producing a single output list, lsof will run in repeat mode. In repeat mode it will produce output, delay, then repeat the output operation until stopped with an interrupt or quit signal. See the +|-r [t[m<fmt>]] option description for more information.


To use it, type the following:
lsof -i:<port>
So in our case, we attempt to bind to port 8080, so running:
lsof -i:8080
Gives us an output like the following:

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
MyApp 50845 dustinkendall … … … … … …

To kill the process, type:
kill <pid>
So in our case:
kill 50845
This will help you get past the java.net.BindException and allow you to bind to that port.