- Required knowledge of dependency injection. Preferably Spring, but can be CDI as well.
- “Any time spent writing configuration is time spent not writing application logic” – (WALLS, Craig – Spring Boot In Action)
What it is?
It is a framework that eases the configuration of a Spring-based application. You can download the dependency of Spring Boot and its related projects as any other dependency of Maven / Gradle, but you can create a project configured using the site: start.spring.io/ (Note: For better visualization, click Switch to the Full version.)
- For this post, the modules will be used: Web (which includes Validation), Thymeleaf, JPA and H2. The project is available in https://github.com/ralphavalon/java-sample-project/tree/with_jpa
Basic Concepts
- The created project with Spring Boot can be in JAR or WAR format. If it is JAR and Web, Spring Boot starts an embedded Tomcat each time it is started.
- Spring Boot needs a class with a method main that executes the method SpringApplication.run
- By default, The @SpringBootApplication annotation is used in this class. Basically it is an annotation that adds other annotations:
- @Configuration – It marks the class as a bean definition source.
- @EnableAutoConfiguration – Add some beans based on Classpath and other settings.
- @ComponentScan – Tells Spring where to look for other components, configurations, and services.
- @EnableWebMvc – If spring-webmvc is on classpath, this annotation is also added, with all Spring MVC configuration.
- If the class that runs SpringApplication.run (let’s call it MainApplication) is in the com.conscious.it package, it’s not necessary to create the beans with default constructor. Spring maps all packages and subpackages from MainApplication package.
Practice
- Whoever used Spring with XML configuration will notice a big difference. Whoever used Spring with configuration in annotations will already know a little better.
- With a Spring Boot project created, it is possible to create a Controller (remembering that it should be created in a sub-package where MainApplication is). The simplest example, a Hello World via Rest:
- Our MainApplication that runs SpringApplication.run
- So when running this class and/or this generated JAR, by default, Spring Boot sets the Context Path to ‘/‘ and the port to 8080. So when starting a Spring Boot project, by default it is accessible in http://localhost:8080
- You can change these settings with the following properties in application.properties
Spring Data JPA
- We have Spring Data JPA and H2 in our classpath. So, let’s create our CRUD:
- CRUD created. Yes, that’s right. You don’t have to implement the CRUD methods. If you don’t know Spring Data JPA, some useful informations:
- CrudRepository<User, Integer> – The first value (User) is the object to be saved on database, annotated with @Entity, and the second value is the type of the id defined with @Id in the object. With this, this interface can be injected and you already can use it. The main methods available will be shown next.
- save – Saves or updates the object in the database
- findAll – Returns all saved objects
- findOne – Returns a object by Id
- delete – Deletes a object in the database
- count – Counts how many objects have in the database
- exists – Returns if the object exists, by Id
- Datasource configuration
- This is the only configuration you need. Relevant information: Note that you do not need to declare the H2 Driver class. Spring Boot is smart enough to know by Classpath. If you want to keep the data when you turn off the application, just use the spring.jpa.hibernate.ddl-auto=update configuration, because the default value is create-drop.
Controller Without REST
- Spring Boot with Web has the following mapped directories:
- src/main/resources/static – Where static files such as JS, fonts and CSS should be.
- src/main/resources/templates – Where the pages should be.
- In my sample project, I created two basic HTMLs. Since we use Thymeleaf, we use HTML for views. One of the great advantages of Thymeleaf is to be simple, so when adding a user to the screen, the HTML would look like this:
- th:text is an attribute of Thymeleaf that overrides the text of the placed tag. You can also change attributes of the HTML itself and even create your Thymeleaf attributes. To know more about how Thymeleaf works: Beyond The Basics – Servlets, JSPs and HTML (Thymeleaf)
That’s it, folks. On the next post, I’ll talk more about Spring Boot configurations, Live Reload, Actuator, Spring Boot tests, how to change a Spring Boot JAR project to WAR and a lot more. If you want to read more subjects of the blog, read the blog track: Tracks – You might have lost 01
Advertisements
bom artigo. ficou claro as vantagens de usar o spring boot na parte web para apis rest apesar de somente 1 exemplo. não ficou claro as vantagens de usar spring boot no Jar. não tem nada ali que indique uma melhora ou uso.
parte do texto esta em ingles e do nada pula pra pt br .. era pra ser assim mesmo ?
gostaria de ver mais um pouco os detalhamentos do spring boot para web. parseamento automatico de objectos mapping request, files filess sempre um problema pra upload salvar gerar.. spring boot resolve isso ? ele tem camadas de cache estatico ? como funciona ?
esperando a continuaçao 02.
Essas coisas vão ser abordadas na parte 02. Posso acrescentar algumas coisas das suas dúvidas, mas das dúvidas que você abordou, são muito mais Spring MVC do que Spring Boot em si. Com relação ao texto estar uma parte em português, já apaguei, não deveria estar ali mesmo. Eu tenho a versão em inglês (que é esse que estamos… https://ralphavalon.wordpress.com/2017/07/04/10040/) e a versão em português que é esse: https://ralphavalonbr.wordpress.com/2017/07/04/10040/ (basicamente botar um BR depois de ralphavalon)…
Pingback: Guide – Spring Boot (Part 02) | Conscious IT
Pingback: Guide – Spring MVC | Conscious IT