12 Aralık 2018 Çarşamba

SpringBoot Custom Starter

Giriş
Açıklaması şöyle
Spring boot uses the @EnableAutoConfigurationannotation to implement the auto-configuration. This annotation import the autoconfigurationImportSelectorclass, which resolves META-INF/spring.factories file when spring boot starts, and then all configuration classes in the file are loaded into memory and registered in the spring container.
Bu dosyalardan Spring'e ait olan örnek bir tanesi şöyle
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration
Kod İçinde Kullanılan Anotasyonlar
Custom Starter veya Custom Autoconfiguration kodlarında @ConditionalXXX anotasyonları sıkça kullanılır. Bu anotasyonlardan bazıları şöyle

Eğer Custom Starter'da hata varsa, hatayı göstermek için AbstractFailureAnalyzer kullanılır

Customer Starter Dosyası Nerededir
Örnek
Kensi Custom Starter nesnemiz için şöyle bir dosya yaratırız.
META-INF/spring.factories
Customer Starter Örnekleri
Örnek
Şöyle yaparız
.
├── main
│   ├── java
│   │   └── com
│   │       └── mycompany
│   │           └── starter
│   │               ├── config
│   │               │   └── GreetingConfiguration.java (1)
│   │               └── service
│   │                   └── GreetingService.java (2)
│   └── resources
│       └── META-INF
│           └── spring.factories (3)
└── test
    ├── java
    └── resources
Dosyanın içi şöyledir
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.mycompany.starter.config.GreetingConfiguration
@Configuration //(1)
@ConditionalOnProperty(name = "greeting.service", value = "enabled", 
  havingValue = "true") //(2)
public class GreetingConfiguration {

  @Bean //(3)
  public GreetingService createGreetingService(){
    return new GreetingService();
  }
}
GreetingService sadece application.properties dosyasında 
greeting.service.enabled=true
ise yüklenir

Örnek
Elimizde şöyle bir kod olsun.
@Configuration  // this is from "shared artifact" 
class MyInfraConfiguration {

}
Dosyaya şu satırı ekleriz.
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.mycompany.myinfra.whatever.MyInfraConfiguration
Örnek
Elimizde şöyle bir kod olsun
@Configuration
public class MyAutoConfiguration {
  private static final Logger logger = LoggerFactory.getLogger(MyAutoConfiguration.class);

  public MyAutoConfiguration() {
  }

  @Bean
  public UserManager userManager() {
    logger.info("UserManager bean start to create.");
    UserManager userManager = new UserManager();
    return userManager;
  }
}
Daha sonra şöyle yaparız. SpringBoot çalışıca userManager() metodunun tetiklendiğini ve log satırının yazıldığını görebiliriz.
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.foo.bar.MyAutoConfiguration


Hiç yorum yok:

Yorum Gönder