Spring Boot Scenario with NetBeans IDE

Today Spring Boot guru Josh Long (@starbuxman) sent me a helpful scenario for getting started with Spring Boot. I've finetuned and translated some aspects to make everything work smoothly in NetBeans IDE.

So, let's get started. Go to http://start.spring.io, click "Switch to the full version", and choose the 'H2', 'web', 'JPA', and 'REST Repositories' checkboxes. Alternatively, you can use the auto completing drop down on the right. You'll get a JAR-based Maven project. Instead, make sure where it says "Packaging" to select "War", as shown below.



Click "Generate Project" at the bottom of the page, which by default will give you a ZIP file named "demo.zip" on disk.

No need to unzip that ZIP file or to go through any kind of complex import process to get the project it contains into NetBeans IDE. Instead, go here:


As can be seen above, go to File | Import Project | From ZIP and then browse to the "demo.zip" file. Click "Import" and NetBeans will unzip your file, open the Maven project, and display it in NetBeans IDE. If some/all of the dependencies have not been downloaded by Maven, you'll see various project problems and errors, which you can solve by right-clicking the project and choosing Build. That will download the Maven dependencies and at the end the project should look nice and neat, as follows:



All the coding we will do from this point onwards will be done in the "DemoApplication.java" file that you see in the "com.example" package above. The import statements we'll need are as follows:

import java.util.Collection;
import java.util.stream.Stream;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.annotation.Id;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.stereotype.Component;

Add each class below beneath the previously existing class in the file. In other words, all the code we'll be working on will be within the same Java source file.

Start by adding a simple JPA entity:

@Entity
class Reservation {
    @Id
    @GeneratedValue
    private Long id;
    private String reservationName;
    public Long getId() {
        return id;
    }
    public String getReservationName() {
        return reservationName;
    }
    public Reservation(String reservationName) {
        this.reservationName = reservationName;
    }
    public Reservation() {
    }
    @Override
    public String toString() {
        return "Reservation{" + "id=" + id + ", reservationName=" + reservationName + '}';
    }
}

Next, we need some way to handle persistence logic, therefore add the following below the previous code in the file, to create a Spring Data JPA repository:

@RepositoryRestResource
interface ReservationRepository extends JpaRepository {
    @RestResource(path = "by-name")
    Collection findByReservationName(@Param("rn") String rn);
}

Finally, again below the previous code in the same file, you'll need to insert some simple sample data, so create a component that gets called on application startup:

@Component
class DummyCLR implements CommandLineRunner {
    @Autowired
    private ReservationRepository repository;
    @Override
    public void run(String... args) throws Exception {
        Stream.of("Josh", "Geertjan", "Pieter").forEach(x -> 
           repository.save(new Reservation(x)));
        repository.findAll().forEach(System.out::println);
    }
}

Now let's run the application, using this tip to do so, which will run the embedded Tomcat provided by Spring Boot and deploy the application to it, correctly running the code from the "public static void main" entry point of the application. We'll be circumventing the NetBeans approach to deploying applications completely and making use of the corresponding features provided by Spring Boot instead.

To do this, right-click the project, click Properties, and rewrite the "Execute Goals" field of the "Run project" action from "package" to "org.springframework.boot:spring-boot-maven-plugin:1.3.2.RELEASE:run", as shown below:


Now, whenever you press F6, you'll be deploying the application to the embedded Tomcat, which you'll also be starting up. In the Output window (Ctrl-4), you can stop the process, i.e., shutdown the embedded Tomcat and undeploy the application.

Run the application via F6 or by choosing "Run" on the project or in the toolbar, which will end up showing you the reservations in the Output window:



Also, when you open your browser to "http://localhost:8080/repositories" you'll see the REST API stood up for you based on your data set, which will initially show an error. "OK," says Josh, at this point. "This is all well and good but let's get serious! This uses an embedded in-memory DB! And there are no operational features. This isn't ready for production! How do you see things like the health of the app? metrics?"

Right-click the "Dependencies" node in the project, choose "Add Dependency", and add "spring-boot-starter-actuator":

After you click "Add" above, the dependency will be added to the POM. Actually, no version should be required since its dependency is managed by Maven in the parent POM. Now, if you restart, i.e., end the process and restart it, you should now be able to hit URLs like the following: localhost:8080/, /reservations, /reservations/1, /reservations/2, etc.:

You should also be able to visit /metrics and /health. "Not bad," says Josh. "Info on the state of the app."


The above instructions are all the basics needed for getting started with Spring Boot. More in follow up blog entries soon.

Comments:

Any reason to need to switch to war, especially since you are running with embedded Tomcat?

Posted by Mark on February 04, 2016 at 07:31 AM PST #

Hej Geertjan,

the association of the goal could be automated using a plugin.

* Add a ProjectOpenHook - http://wiki.netbeans.org/DevFaqListenForOpeningClosingProject
* When a maven project is opened (with some spring-boot specifics as marker like super-pom or what ever) then alter the goal

BR

Posted by guest on February 04, 2016 at 11:54 AM PST #

Hope this isn't too obvious but how would you add a debug action/goal

Posted by Paul Verket on March 08, 2016 at 05:34 PM PST #

Sorry if this is obvious but how would you set up debugging?

Posted by Paul Verket on March 09, 2016 at 12:57 PM PST #

I followed your instructions to the letter, but no ServletInitializer.java file was created. Has something changed in Maven?

Posted by guest on May 02, 2016 at 01:28 AM PDT #

ServletInitializer is not created by Spring Boot. Spring Boots assumes you want to run as a Jar. TO convert to run as a war, you must create that yourself. For instructions - https://spring.io/guides/gs/convert-jar-to-war/

Posted by Mark on May 04, 2016 at 06:11 AM PDT #

I had to change:

* import javax.persistence.Id;

to

import org.springframework.data.annotation.Id;

* @RepositoryRestResource
interface ReservationRepository extends JpaRepository{

to

@RepositoryRestResource
interface ReservationRepository extends JpaRepository<Reservation, Long> {

Posted by poshjosh on May 30, 2016 at 07:51 AM PDT #

Hi Geertjan,

Getting NB to run/shutdown Tomcat can actually be simplified to this as the Run command:

spring-boot:run

Spring on,
Mark :)

Posted by Mark Heckler on May 31, 2016 at 02:43 PM PDT #

Hi Geertjan,

I have seen your webinar on topic Up and Running with Spring Boot in NetBeans IDE, available here:

https://spring.io/blog/2016/03/30/webinar-replay-up-and-running-with-spring-boot-in-netbeans-ide

related to this article, and I think it is great.

Is there a way to add Spring Boot application shutdown via actuator /shutdown or other way before the Run action, to provide easier redeployment of code changes via Run action? I mean without actually having to shutdown manually before Run.

Thanks,
Dejan

Posted by Dejan on August 09, 2016 at 01:15 AM PDT #

Hi,

For those using spring profiles, if you want to pass your spring profile automatically when running the app, just add the following in the the "Set Properties" box when editing the action:

Env.SPRING_PROFILES_ACTIVE=myprofile

Regards

Posted by Charl on September 29, 2016 at 04:10 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
About

Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.

Search

Archives
« January 2017
SunMonTueWedThuFriSat
1
2
3
4
5
6
7
8
9
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    
       
Today