Skip to content

Instantly share code, notes, and snippets.

@vonnenaut
Last active August 9, 2021 10:52
Show Gist options
  • Save vonnenaut/f85485b8269cb9c73608d1fddc893c4b to your computer and use it in GitHub Desktop.
Save vonnenaut/f85485b8269cb9c73608d1fddc893c4b to your computer and use it in GitHub Desktop.
Spring Boot

Spring Boot

Troubleshooting

  • try @Configuration, @EnableAutoConfiguration and @ComponentScan instead of @SpringBootApplication in IntelliJ if it gives errors

 


Setup

Spring Initializer

Spring initializer https://start.spring.io/

Maven

  • a build tool (older than Gradle) for Java projects
  • Maven has goals, different processes that it completes, incl. clean, validate, compile, test, package, verify, install, site and deploy (Lifecycle) and Plugins
  • to find local installation location, go to Maven Window, gear icon (Build Tools Settings) --> Maven Settings and it will be under Local Repository
  • can also download sources and documentation via same-named icon, also in Maven Window

IntelliJ: View --> Tool Windows --> Maven

Lifecycle: clean and install are most important and often used

  • double-click to run

  • target folder is used for all output of build and will appear after first run of compile in Maven Lifecycle (or Build in IntelliJ)

  • install is used to install the package into the local repo and so is also important

  • click on Maven icon at top of Maven window to open CLI for running multiple goals together, e.g., clean install

 

Logging

  • two components to a logging system: (1) API and (2) implementation
  • API is used at application layer directly, in your code, as an interface
  • implementation is what API will use internally, making calls to, to get logging to work
  • slf4j-api is an example of a logging API; requires an implementation
  • logback is an example of a logging implementation, i.e., binding;

Logback

  • successor to log4j
  • can direct logging to variety of dest. incl. db, file, console, email, etc.
  • built using Maven
  • inspired by Linux's iptables
  • configured via XML or groovy
3 components:
  1. loggers for capturing info.
  2. appenders for publishing logging info. to preferred dest.
  3. layouts for formatting info.
Usage
  1. Go to https://mvnrepository.com
  2. search for logback and select latest stable
  3. Copy provided code for Maven (or whichever tool you're using) and add it to your tool's setup file (for Maven, it's pom.xml)

slf4j-api docs http://www.slf4j.org/apidocs/org/slf4j/Logger.html

 


Creating a Multi-Module Project (w/Maven)

  1. start new project
  2. delete src folder
  3. open pom.xml and add line: <packaging>pom</packaging>
  4. create a sub-module via r-click project root --> New --> Module, naming it (core, email, etc.)
  5. Open Maven Window (on right side)
  6. click 'm' icon (execute maven goal)
  7. type and run clean install
  • need to make sure modules are compiled in the correct order for your project (output shows which order they're currently in)

Managing Dependencies

  • copy ``logback.xml` file from previous project or create a new one

  • parent pom.xml settings are inherited by child modules, so use to advantage in declaring things only once that are shared

  • can set version numbers as a sort of variable in properties like the following:

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <logback.version>1.2.5</logback.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
                <version>${logback.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

 

Using a Spring Container

XML-based configuration metadata example

``resources -> beans.xml`

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="..." class="...">  
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>

see: https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans

 


General

  • use Spring Boot DevTools

DB

  • PostgreSQL Driver
  • Spring Data JPA
  • H2 Database
  1. Go to start.spring.io and pick dependencies and versions, generate file, uncompress into project folder.
  2. Open in IntelliJ or VS Code (w/Spring Tools Suite) and let IDE build project.
  3. Create your first Controller
  4. Create a view using Handlebars or another option
  5. Test by going to the location set up in the controller
  • you can just press ctrl+F9 in IntelliJ w/out having to restart the app, so long as you selected Spring Boot DevTools among your dependencies

 

Using Handlebars as View

https://medium.com/techwasti/spring-boot-mustache-hello-world-example-ded94471577c

 

Using HTMLUnit to Simulate User Browser Behavior for Testing

https://htmlunit.sourceforge.io/gettingStarted.html

https://htmlunit.sourceforge.io/dependencies.html

Set up dependencies

  1. Download HTMLUnit to your project (location? /test/...)

  2. create a jar file in IntelliJ: https://www.jetbrains.com/help/idea/compiling-applications.html

  • this will automatically also create a Manifest.txt file which should contain a list of all HTMLUnit-required jars

https://docs.oracle.com/javase/tutorial/deployment/jar/downman.html

NOTE: Folder will by created automatically if you have artifact configured in "Project Structure | Artifacts" and "Include in project build" option is enabled. Otherwise you need to run "Build | Build Artifact..."

  1. Register HTMLUnit Library in the IDE

a. In the IDE, choose Tools > Libraries to open the Libraries Manager.

b. Click New Library and provide a name for the library, e.g. "HTMLUnit"

c. With the "HTMLUnit" library selected, click on the "Add JAR/Folder..." button and select the jar file that was downloaded earlier and click OK to complete alt text (source: netbeans.org)

    **Be sure to add every jar file as an individual library, not the entire folder.**
    Do this by copying the jar files into a new `lib` folder inside the root of your project and r-clicking each jar, one by one, and clicking `add a Library`
  1. Then, add the libraries to the project you are working on.

a. Select the project from the Project view, right-click and select "Properties"

b. Under the Libraries category, click on the "Add Library..." button and choose the HTMLUnit library and click OK to complete

Autoconfigured Tests

https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing.spring-boot-applications.autoconfigured-tests

# Spring Boot
## Troubleshooting
- try `@Configuration`, `@EnableAutoConfiguration` and `@ComponentScan` instead of `@SpringBootApplication` in IntelliJ if it gives errors
&nbsp;
---
## Setup
### Spring Initializer
Spring initializer https://start.spring.io/
### Maven
- a build tool (older than Gradle) for Java projects
- Maven has goals, different processes that it completes, incl. **clean, validate, compile, test, package, verify, install, site and deploy** (Lifecycle) and Plugins
- to find local installation location, go to Maven Window, gear icon (Build Tools Settings) --> Maven Settings and it will be under **Local Repository**
- can also download sources and documentation via same-named icon, also in Maven Window
IntelliJ: `View --> Tool Windows --> Maven`
**Lifecycle**: **clean** and **install** are most important and often used
- double-click to run
- `target` folder is used for all output of build and will appear after first run of `compile` in Maven Lifecycle (or Build in IntelliJ)
- `install` is used to install the package into the local repo and so is also important
- click on Maven icon at top of Maven window to open CLI for running multiple goals together, e.g., `clean install`
&nbsp;
### Logging
- two components to a logging system: (1) **API** and (2) **implementation**
- API is used at application layer directly, in your code, as an interface
- implementation is what API will use internally, making calls to, to get logging to work
- **slf4j-api** is an example of a logging API; requires an implementation
- **logback** is an example of a logging implementation, i.e., binding;
#### Logback
- successor to `log4j`
- can direct logging to variety of dest. incl. db, file, console, email, etc.
- built using Maven
- inspired by Linux's **iptables**
- configured via **XML** or **groovy**
##### 3 components:
1. loggers for capturing info.
2. appenders for publishing logging info. to preferred dest.
3. layouts for formatting info.
##### Usage
1. Go to https://mvnrepository.com
2. search for logback and select latest stable
3. Copy provided code for Maven (or whichever tool you're using) and add it to your tool's setup file (for Maven, it's **pom.xml**)
slf4j-api docs http://www.slf4j.org/apidocs/org/slf4j/Logger.html
&nbsp;
---
## Creating a Multi-Module Project (w/Maven)
1. start new project
2. delete `src` folder
3. open `pom.xml` and add line: `<packaging>pom</packaging>`
4. create a sub-module via `r-click project root --> New --> Module`, naming it (core, email, etc.)
5. Open Maven Window (on right side)
6. click 'm' icon (execute maven goal)
7. type and run `clean install`
- need to make sure modules are compiled in the correct order for your project (output shows which order they're currently in)
### Managing Dependencies
- copy ``logback.xml` file from previous project or create a new one
- parent `pom.xml` settings are inherited by child modules, so use to advantage in declaring things only once that are shared
- can set version numbers as a sort of variable in properties like the following:
```xml
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<logback.version>1.2.5</logback.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
```
&nbsp;
### Using a Spring Container
<details>
<summary>XML-based configuration metadata example</summary>
``resources -> beans.xml`
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
```
see: https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans
</details>
&nbsp;
---
## General
- use Spring Boot DevTools
## DB
- PostgreSQL Driver
- Spring Data JPA
- H2 Database
1. Go to start.spring.io and pick dependencies and versions, generate file, uncompress into project folder.
2. Open in IntelliJ or VS Code (w/Spring Tools Suite) and let IDE build project.
3. Create your first Controller
4. Create a view using Handlebars or another option
5. Test by going to the location set up in the controller
- you can just press ctrl+F9 in IntelliJ w/out having to restart the app, so long as you selected **Spring Boot DevTools** among your dependencies
&nbsp;
## Using Handlebars as View
https://medium.com/techwasti/spring-boot-mustache-hello-world-example-ded94471577c
&nbsp;
## Using HTMLUnit to Simulate User Browser Behavior for Testing
https://htmlunit.sourceforge.io/gettingStarted.html
https://htmlunit.sourceforge.io/dependencies.html
### Set up dependencies
1. Download HTMLUnit to your project (location? /test/...)
2. **create a jar file in IntelliJ:**
https://www.jetbrains.com/help/idea/compiling-applications.html
- this will automatically also create a `Manifest.txt` file which should contain a list of all HTMLUnit-required jars
https://docs.oracle.com/javase/tutorial/deployment/jar/downman.html
**NOTE: Folder will by created automatically if you have artifact configured in "Project Structure | Artifacts" and "Include in project build" option is enabled. Otherwise you need to run "Build | Build Artifact..."**
3. Register HTMLUnit Library in the IDE
a. In the IDE, choose `Tools > Libraries` to open the Libraries Manager.
b. Click `New Library` and provide a name for the library, e.g. "HTMLUnit"
c. With the "HTMLUnit" library selected, click on the "Add JAR/Folder..." button and select the
jar file that was downloaded earlier and click OK to complete
alt text (source: netbeans.org)
**Be sure to add every jar file as an individual library, not the entire folder.**
Do this by copying the jar files into a new `lib` folder inside the root of your project and r-clicking each jar, one by one, and clicking `add a Library`
4. Then, add the libraries to the project you are working on.
a. Select the project from the Project view, right-click and select "Properties"
b. Under the Libraries category, click on the "Add Library..." button and choose the HTMLUnit
library and click OK to complete
## Autoconfigured Tests
https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing.spring-boot-applications.autoconfigured-tests
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment