28 Kasım 2018 Çarşamba

SpringCache @CachePut Anotasyonu - Update İçin Kullanılır Metod Hep Çalıştırılır

Giriş
Açıklaması şöyle
It is a method level annotation. It is used to update the cache before invoking the method. By doing this, the result is put in the cache and the method is executed. It has same attributes of @Cacheable annotation.
Açıklaması şöyle.
CachePut annotation does not cause the target method to be skipped - rather it always causes the method to be invoked and its result to be placed into the cache.
@Cacheable ile farkının açıklaması şöyle.
@CachePut always lets the method execute. It is generally used if you want your cache to be updated with the result of the method execution.
Example: When you want to update a stale data which is cached, instead of blowing the cache completely.

@Cacheable will be executed only once for the given cachekey and subsequent requests won't execute the method, until the cache expires or gets flushed.
condition Alanı
Örnek
Şöyle yaparız
@CachePut(value="addresses", condition="#customer.name=='Tom'")
public String getAddress(Customer customer) {
  return "Adresses";
}
key Alanı
Örnek
Şöyle yaparız.
@CachePut(value = "user", key = "#user.id")
public User createUser(User user) { 
   // store user in db...
}
unless Alanı
Örnek
Şöyle yaparız. 64 karakterden uzun sonuçları cache'e koyar
@CachePut(value="addresses", unless="#result.length()<64")
public String getAddress(Customer customer) {
  return "Adresses";
}
value Alanı
Örnek
Şöyle yaparız
@CachePut(value="employee")
public Employee updateEmployee(Employee employee) {
  // some code
}

25 Kasım 2018 Pazar

SpringBoot application.properties H2 Ayarları

Giriş
H2 ve HSQLDB farklı şeyler ve ben hep bu ikisini karıştırıyorum. jar dosyası com.h2database.h2 dizininde. Driver sınıfı ise org.h2.Driver ismine sahip.

Bu ayarları yapınca SpringBoot bizim için bir EmbeddedDatabaseBuilder yaratır

Maven
Şu satırı dahil ederiz.
<dependency>
  <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>test</scope>
</dependency>
Şu satırı dahil ederiz. scope olarak runtime seçilmesinin sebebi, derleme için H2'ye mahsus bir kodun kullanılmaması ancak uygulamayı çalıştırmak için H2 gerekiyor.
<dependency>
  <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>runtime</scope>
</dependency>
application-test.properties
url Alanı
Bu alan en önemli şey. Eğer bellekte veri tabanı istiyorsak "jdbc:h2:mem:dbname" şeklinde kullanırız. Eğer dosya veri tabanı istiyorsak "jdbc:h2:pathtofile" şeklinde kullanırız

Örnek
Şöyle yaparız. Burada veri tabanı integration test için kullanılıyor. Bu yüzden ilave parametreler veriliyor.
"jdbc:h2:mem:test:sample;DB_CLOSE_ON_EXIT=FALSE;
INIT=RUNSCRIPT FROM 'classpath:schema-generator.sql';"
Örnek
Bellekte veri tabanı için şöyle yaparız. h2:mem şeklinde kullanılıyor
# Data source
spring.datasource.url=jdbc:h2:mem:test
spring.datasource.username=admin
spring.datasource.password=admin
spring.datasource.driver-class-name=org.h2.Driver
Örnek
Dosyada veri tabanı için şöyle yaparız.
spring.datasource.url=jdbc:h2:~/test
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password= 
Örnek
Bellekte veri tabanı için şöyle yaparız. h2:mem şeklinde kullanılıyor
spring:
    datasource:
        database: HSQL
        driverClassName: org.h2.Driver
        url: jdbc:h2:mem:MyDBName
        username: sa
        password:
Örnek
H2 web console ayarı için şöyle yaparız.
# H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:file:~/mydb.db
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
Örnek
H2 web console ayarı için şöyle yaparız
server:
  port: ${port:8080}

spring:
  application:
    name: flyway-demo

  datasource:
    driver-class-name: org.h2.Driver
    username: sa
    password:
    url: "jdbc:h2:mem:db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;DATABASE_TO_LOWER=TRUE;CASE_INSENSITIVE_IDENTIFIERS=TRUE"
  h2:
    console:
      enabled: true
      path: /h2-console
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: none

H2 Konsol

http://localhost:8080/h2-console
http://localhost:8080/h2-console adresine gideriz. Böylece tabloları ve veriyi görebiliriz.. Diğer girdiler şöyle
JDBC URL: jdbc:h2:mem:db

User Name: sa

Password: <empty>
Şeklen şöyle
SQL Çalıştırmak
Şeklen şöyle


Şeklen şöyle






23 Kasım 2018 Cuma

SpringContext @Lazy Anotasyonu

Giriş
Şu satırı dahil ederiz
import org.springframework.context.annotation.Lazy;
1. Bu anotasyonu kullanmadan önce her şeyi lazy yapmak istersek şöyle yaparız
// In application.properties file
spring.main.lazy-initialization=true

// In application.yml file
spring:
  main:
    lazy-initialization: true
veya lazyInitialization() metodu kullanılır. Şöyle yaparız
@SpringBootApplication public class LazyApplication { public static void main(String[] args) { new SpringApplicationBuilder(LazyApplication.class) .lazyInitialization(true) .build() .run(args); } }

2. Sadece A ve B arasında lazy ilişki kurmak istersek @Lazy kullanılabilir.

- @Lazy anotasyonu A sınıfında Constructor Injection, Setter Injection ve Field Injection ile kullanılabilir. Ayrıca @Configuration ile de kullanılabilir.
- Eğer B sınıfının da yaratılmasını istemiyorsak yani her iki tarafında da sonradan yaratılmasını istiyorsak, B sınıfı da @Lazy olarak işaretlenmelidir. Yani bu anotasyon hem A da hem de B de kullanılmalıdır.

Açıklaması şöyle.
By default, the Spring IoC container creates and initializes all singleton beans at the time of application startup. We can prevent this pre-initialization of a singleton bean by using the @Lazy annotation.

The  @Lazy annotation may be used on any class, directly or indirectly annotated with the  @Component or on methods annotated with the @Bean.
Her kullanımda Spring A sınıfında kullanılmak üzere bir proxy üretir. Açıklaması şöyle.
Spring uses a proxy instead of the real object at the injection point. This proxy delays the initialization of the underlying object until it is first used.
Constructor Injection İle Kullanımı
Bu kullanımla ilgili Circular Dependency yazısına bakılabilir.

Örnek ver

Field Injection İle Kullanımı
Açıklaması şöyle.
Lazy annotation may also be placed on injection points marked with Autowired or Inject: In that context, it leads to the creation of a lazy-resolution proxy for all affected dependencies, as an alternative to using ObjectFactory or Provider.
Şöyle yaparız.
@Autowired
@Lazy
private EventPublishService eventPublishService;
Setter Injection İle Kullanımı
Örnek ver

Configuration İle Kullanımı
Açıklaması şöyle. B sınıfında kullanılır.
If Lazy is present on a @Configuration class, this indicates that all @Bean methods within that @Configuration should be lazily initialized.
Örnek
Şöyle yaparız.
@Lazy
@Configuration
@ComponentScan(...) // will be lazily initialized with config
public class LazyConfiguration {

  @Bean
  public SomeBean beanName() { // will be lazily initialized with config
    return new SomeBean();
  } 

  @Bean
  public OtherBean beanName() { // will be lazily initialized with config
    return new OtherBean();
  }     
}
Örnek
Şöyle yaparız
@Lazy
@Bean
public PasswordEncoder encoder() {
  return new BCryptPasswordEncoder();
}
Örnek
Şöyle yaparız
@SpringBootApplication
public class LazyApplication {

  @Bean("eagerBean")
  public void eagerBean() {
    System.out.println("Eager Bean is Created !!");
  }


  @Lazy
  @Bean("lazyBean")
  public void lazyBean() {
    System.out.println("Lazy Bean is Created !!");
  }
}