Ihre Browserversion ist veraltet. Wir empfehlen, Ihren Browser auf die neueste Version zu aktualisieren.

SpringBoot REST API best practices

SpringBoot3 and Records

REST API reads intros

Validation

Controller advice

Paging

Testing

RestTemplate

RestTemplateBuilder

Error Handling

HATEOAS

REACTIVE

SPRING AOP

SPRING EVENTS

Consumer-Driven Contract with Pact

Spring Integration

Spring for Apache Kafka

Constructor vs Setter/Field DI

  • The IoC container makes sure that all the arguments provided in the constructor are available before passing them into the constructor.
  • Constructor injection helps us to identify if our bean is dependent on too many other objects.
  • Constructor injection simplifies writing unit tests. Mockito, we can create mock objects that we can then pass into the constructor.
  • Constructor injection helps in creating immutable objects. With setter injection, it’s possible to inject the dependency after creation, thus leading to mutable objects which, among other things, may not be thread-safe in a multi-threaded environment and are harder to debug due to their mutability.
  • https://reflectoring.io/constructor-injection/

ServerLess

Serverless applications take advantage of modern cloud computing capabilities and abstractions to let you focus on logic rather than on infrastructure. In a serverless environment, you can concentrate on writing application code while the underlying platform takes care of scaling, runtimes, resource allocation, security, and other “server” specifics.

Springboot Azure

Spring Cloud Azure is an open-source project that provides seamless Spring integration with Azure services. It gives developers a Spring-idiomatic way to connect and consume Azure services, with only need few lines of configuration and minimal code changes.

Why SpringBoot Servless and Functions on Azure

Microsoft invests more than USD1 billion annually on cybersecurity research and development. Microsoft seems to prove over and over again its focus on cloud and the Java ecosystem is the new normal.

SpringBoot Reactive guide

WebFlux and Functional EndPoints: need for a non-blocking web stack to handle concurrency with a small number of threads and scale with fewer hardware resources.

Spring and Paging

Spring Boot Version

Controller Advice, mulitple handlers, exception handling vnd

To reduce the applicable classes down by package

Validation with Spring

Serve Static Resources with Spring

Spring Boot comes with a pre-configured implementation of ResourceHttpRequestHandler to facilitate serving static resources. By default, this handler serves static content from any of /static, /public, /resources, and /META-INF/resources directories that are on the classpath. Since src/main/resources is typically on the classpath by default, we can place any of these directories there.

Spring DI patterns

There are three ways Spring lets you declare the dependencies of your class using annotations. Field injection (the bad), Setter injection (the ugly) and finally Constructor injection (the good).... why... read...

Add Proxy to RestTemplate

When the server is configured in system property or JVM starting argument, it impacts the overall application. HTTP Proxy server for each RestTemplate can be configured for SimpleClientHttpRequestFactory which is a default implementation of ClientHttpRequestFactory interface.

Jackson serialization

Jackson ObjectMapper and MappingJackson2HttpMessageConverter

To have different deserialization configurations you must have different ObjectMapper instances but out of the box Spring uses MappingJackson2HttpMessageConverter which is designed to use only one instance.

Functional Programming patterns with Java8 Lambda's

ClientHttpRequest Interceptor

Spring provides the ClientHttpRequest Interceptor interface, which can intercept requests and modify them or enhance the corresponding information before they are sent to the server.

RestTemplate Error Handling

RestController PreHandle logging

Extend CommonsRequestLoggingFilter and overwrite shouldNotFilter method like described here

SpringBoot Security and JWT

Transactions and ACID

@Transactional only rolls back transactions for unchecked exceptions. For checked exceptions and their subclasses, it commits data. So although an exception is raised here, because it's a checked exception, Spring ignores it and commits the data to the database, making the system inconsistent.

Javers and Springboot

When dealing with mutable data we usually have only the last state of an entity stored in a database. Fortunately, we have great tools like JaVers. JaVers is an audit log framework that helps to track changes of entities in the application.

BPMN2.0 and Springboot

Deserialize JSON from Springboot resource file

ObjectMapper objectMapper = new ObjectMapper();

Employee employee = objectMapper.readValue(new ClassPathResource( "testcase/employee.json").getFile(), Employee.class);


Spring Boot and Multi-Threading

Multi-threading is similar to multitasking, but enables the processing of executing multiple threads simultaneously, rather than multiple processes. The CompletableFuture, introduced in Java 8, provides an easy way to write asynchronous, non-blocking and multi-threaded code.

 

Autoconfiguration

@Conditional (since version 4.0) annotation and beans, the basis for everything Spring Boot does. A Spring application context (all the framework support your application needs, like databases, JMS, MongoDB, Web support and REST) contains an object graph that makes up all the beans that our application needs at runtime. Spring's @Conditional annotation allows us to define conditions under which a certain bean is included in that object graph. Anywhere we define a Spring bean, we can optionally add a condition. Only if this condition is satisfied will the bean be added to the application context. External libraries can contain conditional beans. Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added.

Final Answer: What is Spring Boot?

Spring Boot is just a couple of AutoConfigurations classes (== normal Spring @Configurations), that create @Beans for you if certain @Conditions are met.

Three of the most important conditions are

  1. @ConditionalOnClass. Checking for dependencies or rather specific classes of dependencies (think: Tomcat, HikariCP, etc).

  2. @ConditionalOnProperty. Self-explanatory.

  3. @ConditionalOnMissingBean. If the user specified his own, e.g. DataSource, already, then Spring Boot won't try to create its auto-configured one.

Report Output

 

The auto-configuration report contains information about the classes that Spring Boot found on the classpath and configured automatically. It also shows information about classes that are known to Spring Boot but were not found on the classpath.

And, because we've set debug=true, then we see it in our output:

================== CONDITIONS EVALUATION REPORT ============================ Positive matches: ----------------- AopAutoConfiguration matched: - @ConditionalOnClass found required classes

 

JMeter and SpringBoot REST services

It is important to ensure effective performance for software applications, and software testing is often required to ensure that the application runs without any failures. This blog on JMeter will provide in-depth knowledge about this load testing tool for analyzing and measuring the performance in the following sequence.

Spring the ultimate guides

Whatever you're building, these guides are designed to get you productive as quickly as possible – using the latest Spring project releases and techniques as recommended by the Spring team.

All the Spring Guides Together

SpringBoot Milestones

Spring, Swagger uploading files

Derived Query Methods in Spring

Spring Data JPA leverages this idea in the form of a method naming convention.

So what is the entity fetching strategy anyway?

When JPA loads an entity, it also loads all the EAGER or “join fetch” associations too. As long as the persistence context is opened, navigating the LAZY association results in fetching those as well, through additionally executed queries.Planning your fetching strategy from the very beginning, and adjusting it all along the development cycle isn’t a “premature optimization”; it’s just a natural part of any ORM design.

The LazyInitializationException is undoubtedly one of the most common exceptions you can get when using Hibernate. Unfortunately, JPA 1.0 decided that @ManyToOne and @OneToOne should default to FetchType.EAGER, so now you have to explicitly mark these two associations as FetchType.LAZY:

The solution, DTO projections with Spring Data Projections and Open Projections and the most beautiful Dynamic Projections

Spring Data JPA Specification

Spring Data JPA was created primarily to allow easy query creation with query generation by method name. However, sometimes, we need to create complex queries and cannot take advantage of a query generator. The Spring Data JPA provides a repository programming model that starts with an interface per managed domain object. Defining these interfaces serves two purposes: first, by extending the JpaRepository, we get a bunch of generic CRUD methods, like save, findAll, delete, and so on.

To Create Complex Queries, Why Specification?

Yes, complex queries can be build using the Criteria API. For any complex-enough API – searching/filtering your resources by very simple fields is simply not enough. A query language is more flexible and allows you to filter down to exactly the resources you need.

Hibernate specifics

Strategy Design Pattern and Lambda's

Read this wonderful post about different classifications of patterns!!!

The idea of the strategy pattern is to define a family of algorithms, encapsulate what varies into separate classes and make their objects interchangeable in the context. Varies here means: may change over time due to the evolving requirements.

Lambda expressions have changed the world in Java, and we can effectively use lambda expressions to avoid writing a lot of ceremonial code. As far as the strategy design pattern is concerned we don't have to create a hierarchy of classes. Instead, we can directly pass the strategy implementation of the interface as a lambda expression to the context.

Take one functional interface that fits your family of algorithms, declare them all statically in one place (single class).

All You Need To Know For Migrating To Java 11

We haven't fully immersed ourselves in Java 10 yet, and Java 11 is here. Java 11 is important for more than just a few reasons. Oracle has revamped its support model and come up with a release train that'll bring rapid updates, about every 6 months.

Negate a Predicate with Java 11

The Predicate.not() static method has been added to Java 11 in order to negate an existing Predicate.

people.stream() .filter(Predicate.not(Person::isAdult)) .collect(Collectors.toList());

 

Mockito

Migrating from JUnit 4 to JUnit 5

Let's start with the previous version – JUnit 4 has some clear limitations:

  • The entire framework was contained in a single jar library. The whole library needs to be imported even when only a particular feature is required. In JUnit 5, we get more granularity and can import only what is necessary
  • One test runner can only execute tests in JUnit 4 at a time (e.g. SpringJUnit4ClassRunner or Parameterized ). JUnit 5 allows multiple runners to work simultaneously
  • JUnit 4 never advanced beyond Java 7, missing out on a lot of features from Java 8. JUnit 5 makes good use of Java 8 features
  1. Migrating from a JUnit4-Based Runner
  2. junit 5 migration for Springboot applications
  3. Junit5 and @RunWith
  4. Guide to JUnit5
  5. how to integrate Mockito with the JUnit 5 extension model
  6. Unit testing with JUnit 5, Mockito, and Hamcrest

Java 8 Date – LocalDate, LocalDateTime, Instant

Java 8 Date Time API is one of the most sought after change for developers. Java has been missing a consistent approach for Date and Time from start and Java 8 Date Time API is a welcome addition to the core Java APIs.

Time Complexity of Java Collections

we'll talk about the performance of different collections from the Java Collection APIUsually, when we talk about time complexity, we refer to Big-O notation. Simply put, the notation describes how the time to perform the algorithm grows with the size of the input. This notation approximately describes how the time to do a given task grows with the size of the input. ... Roughly speaking, on one end we have O(1) which is “constant time” and on the opposite end we have O(xn) which is “exponential time”.

  1. Constant means that the time is always the same, it doesn't matter the length of the List
  2. Linear time means the longer the ArrayList is (more object it contains) the longer time the op will take, linear means that the more the List grows, the longer is the time, but in a linear way, so for example to perform a linear operation on a list that contains 20 elements it will take two times the time needed for a list with 10 elements.
Performing the fastest search - which collection should i use?
  • If you need fast access to elements using indexArrayList should be choice.
  • If you need fast access to elements using a key, use HashMap.
  • If you need fast add and removal of elements, use LinkedList (but it has a very poor seeking performance).
Which collection is best for insertion and deletion?
1) As explained above the insert and remove operations give good performance ( O(1) ) in LinkedList compared to ArrayList( O(n) ). Hence if there is a requirement of frequent addition and deletion in application then LinkedList is a best choice.
Which collection is best for sorting in Java?
HashSet has slightly better performance than LinkedHashSet , but its iteration order is undefined. TreeSet is ordered and sorted, but slower. TreeMap is ordered and sorted, but slower. LinkedList has fast adding to the start of the list, and fast deletion from the interior via iteration.
Which is better ArrayList or LinkedList in Java?
ArrayList is faster than LinkedList if I randomly access its elements. ... ArrayList has direct references to every element in the list, so it can get the n-th element in constant time. LinkedList has to traverse the list from the beginning to get to the n-th element. LinkedList is faster than ArrayList for deletion

Intellij Java and Springboot

Hosted by WEBLAND.CH