25 Mart 2019 Pazartesi

SpringBoot ApplicationConversionService Sınıfı

Giriş
StringToEnumConverterFactory, StringToEnumIgnoringCaseConverterFactory sınıflarını kullanıma açar. İçi şöyledir
/** Spring Framework code */
public static void addApplicationConverters(ConverterRegistry registry) {
  ...
  registry.addConverterFactory(new StringToEnumIgnoringCaseConverterFactory());
}
configure metodu
Şöyle yaparız
@Configuration
class CustomWebMvcConfigurer implements WebMvcConfigurer {
  @Override
  public void addFormatters(final FormatterRegistry registry) {
    ApplicationConversionService.configure(registry);
  }
}

17 Mart 2019 Pazar

SpringWebFlux

Giriş
Spring tarafından geliştirilen Reactive Streams Specification uyumlu bir altyapı. RxJava ile aynı şeyi yapar. Spring 5 ve Java 8+ ile çalışır.

Açıklaması şöyle.
There's Spring Reactive, Akka, and Vertx, but they work off a single threaded event loop (though they do have Schedulers, which are really a workaround to allow multi-threading).
Açıklaması şöyle
WebFlux offers two programming models: 

- annotated controllers
- functional endpoints
@EnableWebFlux Anotasyonu
Açıklaması şöyle
If you want to keep Spring Boot WebFlux features and you want to add additional WebFlux configuration, you can add your own @Configuration class of type WebFluxConfigurer but without @EnableWebFlux.

If you want to take complete control of Spring WebFlux, you can add your own @Configuration annotated with @EnableWebFlux.

Maven
Şu satırı dahil ederiz
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
Spring gelişimi içindeki tarihçesi şöyle. Yani 2017 yılından itibaren Reactive desteği bulunuyor.


WebFlux WebServer Olarak Altta Netty Kullanır
Şeklen şöyle
Açıklaması şöyle
Netty is the default web server for Spring WebFlux applications (not Jetty or Tomcat, which are typical for SpringMVC). Since the Spring team designed WebFlux to be asynchronous and event-driven, Netty is the obvious choice because it uses the exact same model.
Ancak istenirse Tomcat kullanılabilir. Açıklaması şöyle
WebFlux is supported on Tomcat, Jetty, Servlet 3.1+ containers, as well as on non-Servlet runtimes such as Netty and Undertow. Netty is most commonly used for async and non-blocking designs, so WebFlux will default to that. You can easily switch between these server options with a simple change to your Maven or Gradle build software.

This makes WebFlux highly versatile in what technologies it can work with and allows you to easily implement it with existing infrastructure.
Project Reactor
Açıklaması şöyle
The reactive streams specification has many implementations. Project Reactor is one of the implementations. The Reactor is fully non-blocking and provides efficient demand management. The Reactor offers two reactive and composable APIs, Flux [N], and Mono [0|1], which extensively implement Reactive Extensions. Reactor offers Non-Blocking, backpressure-ready network engines for HTTP (including Websockets), TCP, and UDP. It is well-suited for a microservices architecture.
Açıklaması şöyle
- Project Reactor is VMware/Spring’s implementation of Reactive Streams.
- RxJava is Netflix’s implementation.
Project Reactor Java 8+ ile kullanılır. Açıklaması şöyle.
Reactor on the other hand is Java 8+ only, so it can make full use of the new Java 8 native classes. Since Spring 5.0 is also Java 8+ only, that means Reactor has the edge in this regard.
Project Reactor impot'ları için şöyle yaparız
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
Project Reactor Subscriber Nedir
Açıklaması şöyle
Subscriber: Receives and processes events emitted by Publisher. Multiple Subscribers can link to a single Publisher and respond differently to the same event. Subscribers can be set to react:

- onNext, when it receives the next event.
- onSubscribe, when a new subscriber is added
- onError, when an error occurs with another subscriber
- onComplete, when another subscriber finishes its task
Project Reactor Flux Nedir
[0-N) arası nesne üretirFlux Sınıfı yazısına taşıdım.

Project Reactor Mono Nedir
Mono Sınıfı yazısına taşıdım.

Flux ve Monu'nun Farkları Nedir
Açıklaması şöyle.
First, it should be noted that both a Flux and Mono are implementations of the Reactive Streams Publisher interface. Both classes are compliant with the specification, and we could use this interface in their place:

Spring Reactive JPA İle Birlikte Çalışmıyor
Açıklaması şöyle. Bunun yerine ReactiveCrudRepository'den kalıtan sınıfları kullanmak lazım. MongoDB Reactive yazısına bakabilirsiniz. Ayrıca Integrating Hibernate Reactive with Spring yazısına bakabilirsiniz.
For example, say we choose Spring Reactive. Yay, we can make concurrent asynchronous calls out to various microservices. We can also use the latest in NoSQL data stores. This was all a great decision. However, over time, we realize that we have a small amount of data where integrity of the data is very important. We find that we want to use a relational database to solve this and then incorporate JPA on this database for easier interaction. However, our choice of Spring Reactive has disallowed this because it requires all I/O to be asynchronous (JPA is synchronous database calls).

15 Mart 2019 Cuma

SpringContext FactoryBean Arayüzü - Belirtilen Tipi Yaratır ve Bean Olarak Kullanabilmeyi Sağlar

Giriş 
Şu satırı dahil ederiz.
import org.springframework.beans.factory.FactoryBean;
Bu sınıfın döndürdüğü sınıf tipini @Component olarak işaretleyeme gerek yok. Spring bu işi bizim için yapıyor. Açıklaması şöyle.
The object created by the FactoryBean are managed by Spring, but not instantiated or configured by Spring.
Döndürdüğümüz nesne tipini @Autowire olarak kullanabiliriz.

FactoryBean Nedir?
Açıklaması şöyle. Yani belirtilen tipten bir nesne yaratır ve bu nesne bean kabul edilir. Dolayısıyla  @Autowired olarak inject edilebilir.
A FactoryBean is an interface that you, as a developer, implements when writing factory classes and you want the object created by the factory class to be managed as a bean by Spring...
getObject() metodu
Örnek
Şöyle yaparız. MessageDigest nesnesi artık @Autowired olarak kullanılabilir. Burada isSingleton() true dönüyor
public class MessageDigestFactoryBean implements FactoryBean<MessageDigest>{

    private String algorithmName = "MD5";
    private MessageDigest messageDigest = null;

  @Override
  public MessageDigest getObject() throws Exception {
    return messageDigest;
  }

  @Override
  public Class<?> getObjectType() {
    return MessageDigest.class;
  }

  @Override
  public boolean isSingleton() {
    return true;
  }

  @PostConstruct
  public void postConstructHandler() throws NoSuchAlgorithmException {
    messageDigest = MessageDigest.getInstance(algorithmName);
  }

  public void setAlgorithmName(String algorithmName) {
    this.algorithmName = algorithmName;
  }
}
getObjectType metodu
Şöyle yaparız.
ublic class SearcherFactory implements FactoryBean<Searcher> {

  @Override
  public Class<Searcher> getObjectType() {
    return Searcher.class;
  }
    .... 
}
isSingleton metodu
Bu metod true döndürürse getObjet() metodu bir kere çağrılır. Bu metod false döndürürse bean prototype kabul edilir ve getObject() metodu her seferinde çağrılır.
Örnek
Şöyle yaparız.
public boolean isSingleton() {
  return true;
}

13 Mart 2019 Çarşamba

SpringMVC @ControllerAdvice Anotasyonu - Global Exception Handling, Binding vs İçindir

Giriş
Şu satırı dahil ederiz
import org.springframework.web.bind.annotation.ControllerAdvice;
Açıklaması şöyle.
Specialization of @Component for classes that declare @ExceptionHandler, @InitBinder, or @ModelAttribute methods to be shared across multiple @Controller classes.
Açıklaması şöyle
Any class annotated with @ControllerAdvice becomes a controller-advice that support three types of methods: Model enhancement methods, Binder initialization methods and Exception handling methods
Bu sınıfın daha kolayı @RestControllerAdvice anotasyonu. Açıklaması şöyle
@RestControllerAdvice is just a syntactic sugar for @ControllerAdvice + @ResponseBody ...

Controller exception fırlatırsa, exception'ı içeren bir ResponseEntity döndürebilmeyi sağlar. ResponseEntityExceptionHandler sınıfından kalıtabilir.

Exception Handling
@ExceptionHandler Anotasyonu yazına taşıdım

basePackageClasses Alanı
Örnek
Şöyle yaparız.
@ControllerAdvice(basePackageClasses = RepositoryRestExceptionHandler.class)
public class GenericExceptionHandler {

  @ExceptionHandler
  ResponseEntity handle(Exception e) {
    return new ResponseEntity("Some message", new HttpHeaders(), HttpStatus.BAD_REQUEST);
  }
}