Giter Site home page Giter Site logo

springboot-essentials's Introduction

Spring Boot Essentials

Spring Boot course from DevDojo Academy

Topics

  • @Component, @Autowired and @SpringBootApplication
  • Hot Swap
  • Spring Initializr
  • CRUD (GET, READ, UPDATE and DELETE)
  • JPA (MySQL)
  • Exception Handling
  • Paging and Sorting
  • Spring Security
  • OpenAPI
  • Spring Actuator
  • Prometheus
  • Grafana

Notes

  • Avoid return the object prefers use a ResponseEntity
@GetMapping
public List<Anime> listAll() {} ๐Ÿ˜•
public ResponseEntity<List<Anime>> listAll() {} โœ…
  • Use config to get stack trace when pass trace param /animes/6?trace=true (Not Found)
  • JpaRepository has @NoRepositoryBean
  • Use a Handler to get errors and set a template to response ( Example: RestExceptionHandler)
{
    "title": "Resource not Found",
    "status": 404,
    "details": "Anime Not Found",
    "timestamp": "2022-04-05T20:17:57.3394187",
    "developerMethod": "academy.devdojo.springbootessentials.exception.ResourceNotFoundException"
}
  • It's possible ignore errors when use transaction @Transactional(dontRollbackOn = Exception.class)
  • Configure logger to log hibernate SQL only when level is DEBUG
logging:
  level:
    org:
      hibernate:
        SQL: DEBUG
  • RestTemplate is used to simulate requests to your API
  • Use a mock database to create tests with JPA, such as H2
<!-- Mock database -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope> <!-- Set scope -->
</dependency>
  • Change display name tests format using @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
void should_Save_Persist_Anime_When_Successful() -> "should Save Persist Anime When Successful"
  • Two ways to get exceptions in tests
Assertions.assertThatThrownBy(() -> animeRepository.save(anime))
        .isInstanceOf(ConstraintViolationException.class);

Assertions.assertThatExceptionOfType(ConstraintViolationException.class)
        .isThrownBy(() -> animeRepository.save(anime))
        .withMessageContaining("The name of this anime cannot be empty");
  • Use @ExtendWith(SpringExtension.class) to integrates the Spring TestContext Framework into JUnit 5's Jupiter programming model
  • When my method doesn't return a result I can use this Mock
Assertions.assertThatCode(() -> animeService.delete(1))
                .doesNotThrowAnyException();
  • Get port using @LocalServerPort (Example)
@Value("${local.server.port}")
public @interface LocalServerPort {
}
  • Mock database as a Bean (@MockBean)
  • Set Maven profile for Integration Tests
<profiles>
    <profile>
        <id>integration-tests</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <configuration>
                        <includes>
                            <include>**/*IT.*</include>
                        </includes>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>
  • Get XSRF in Postman using JavaScript
var xsrfCookie = postman.getResponseCookie("XSRF-TOKEN");
postman.setEnvironmentVariable("x-xsrf-token", xsrfCookie.value);

  • Protect specific routes using @PreAuthorize("hasRole('ADMIN')")
  • Hidden parameter when you're using Swagger
@Parameter(hidden = true)

Get Started

Start database container docker:

docker-compose up -d

Run spring application:

mvn clean install package

java -jar .\target\springboot-essentials-0.0.1-SNAPSHOT.jar

It's possible change database config editing docker-compose.yml

Test

Run all tests (unit and integration tests)

mvn test 

Run only integration tests

mvn test -Pintegration-tests 

Collection Postman folder file

Playlist


Developed by Jean Jacques

springboot-essentials's People

Contributors

jjeanjacques10 avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.