<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Betül Şahin on Medium]]></title>
        <description><![CDATA[Stories by Betül Şahin on Medium]]></description>
        <link>https://medium.com/@betulsahinn?source=rss-c720cfe5ef8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KWGRSXOIS1KWRmuquhDnsA.jpeg</url>
            <title>Stories by Betül Şahin on Medium</title>
            <link>https://medium.com/@betulsahinn?source=rss-c720cfe5ef8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 18:59:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@betulsahinn/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spring Boot ile Unit Test Yazmak]]></title>
            <link>https://betulsahinn.medium.com/spring-boot-ile-unit-test-yazmak-f1e4fc1f3df?source=rss-c720cfe5ef8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1e4fc1f3df</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[junit-5]]></category>
            <category><![CDATA[mockito]]></category>
            <dc:creator><![CDATA[Betül Şahin]]></dc:creator>
            <pubDate>Thu, 10 Feb 2022 15:41:19 GMT</pubDate>
            <atom:updated>2022-02-10T15:41:19.947Z</atom:updated>
            <content:encoded><![CDATA[<p>Bu yazıda <strong><em>Spring Boot</em></strong> uygulamalarında <strong><em>unit test</em></strong> yazmayı konuşacağız. Başlangıçta test kavramına temel bir giriş yapıyor olacağız. Konudan bağımsız olarak unit testlerin nasıl yazıldığına bakacağız. Test yazımı bakış açısını anlamaya çalışacağız. Ardından ise <em>Controller </em>ve <em>Service </em>sınıflarına nasıl birim testi yazıldığını inceleyeceğiz.</p><p><em>Bu yaz öğrenci olarak katılmış olduğum </em><a href="https://www.linkedin.com/company/gittigidiyor/"><em>GittiGidiyor</em></a><em> — </em><a href="https://www.linkedin.com/company/kodluyoruz/"><em>Kodluyoruz</em></a><em> &amp; </em><a href="https://www.linkedin.com/company/patikadev/"><em>Patika.dev</em></a><em> işbirliğiyle düzenlenen GittiGidiyor Java Spring Framework Bootcamp’inde öğrenmiş olduklarımı derledim. Bizlerle bilgi ve tecrübelerini içtenlikle paylaşan eğitmenimiz </em><a href="https://tr.linkedin.com/in/koray-g%C3%BCney-77599992"><em>Koray Güney</em></a><em>’e teşekkür ediyorum.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8x2WsIxdqHcIrCn7MjfPww.jpeg" /></figure><h3>Unit Test Nedir ?</h3><p><em>Unit test yazmak</em> önemli bir konu ve uygulamayı geliştiren kişinin sorumluluğunda.</p><p><a href="https://tr.wikipedia.org/wiki/Birim_testi"><strong>Wikipedia</strong></a><strong> </strong>’dan unit test tanımına bakalım.</p><blockquote>Birim testi, yazılım programlamasında bir tasarım ve geliştirme yöntemidir. Bu yöntemde yazılımcı <em>yazılım kodunu oluşturan birimlerin kullanıma hazır olduğuna iknâ olur.</em> Birim, bir bilgisayar uygulamasında test edilebilecek en küçük bölüme denir.</blockquote><p>Farklı test tipleri var. <strong><em>Unit test</em></strong> ve <strong><em>entegrasyon testi</em></strong> bunlardan bazıları.</p><h4>Test Metodu Nasıl Yazılır ?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*tPPHw2hE1vtUJmwRhaTwCg.jpeg" /></figure><p>Testlerimizi <strong><em>src/test</em></strong> klasörü altına yazıyoruz. Directory yapısı bizi bu konuda yönlendiriyor.</p><p>Default olarak gelen test sınıfını silip <strong><em>SampleUnitTestClass</em></strong> sınıfını oluşturuyoruz.</p><p>İlk olarak hiçbir şey yazmadan aşağıdaki gibi bir test metodu oluşturalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9842d3b6633ed33424ef6ad3d0676ae3/href">https://medium.com/media/9842d3b6633ed33424ef6ad3d0676ae3/href</a></iframe><ul><li><strong>void — </strong>Test metodları her zaman void olarak yazılır. Çünkü test metodlarını herhangi bir yerde çağırıp kullanmıyoruz. Ayrıca bu tüm birim testlerin birbirinden bağımsız olduğu anlamına geliyor.</li><li><strong>@Test — </strong>Test metodlarımızın başına her zaman bu anotasyonu koyuyoruz. <strong><em>org.junit.jupiter.api</em></strong> paketinde bulunuyor. <strong><em>JUnit</em></strong> kütüphanesi Spring içerisinde default olarak gelmektedir ve unit test yazabilmemizi sağlamaktadır. Java 8 ile beraber <a href="https://junit.org/junit5/docs/current/user-guide/"><strong><em>JUnit 5</em></strong></a> yayınlandı.</li></ul><p><em>Testimizi koşturmak için metodun solunda bulunan </em><strong><em>run </em></strong><em>butonuna tıklıyoruz. Aşağıdaki çıktıyı alıyor olacaksınız. Sağ alt bölümde test sonucu yer alıyor.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mep-TxYBwUr6QW-aO-IIfw.jpeg" /></figure><p><strong>Haydi başlayalım ! </strong>💪</p><p><strong><em>SampleUnitTestClass</em></strong> sınıfına <strong><em>Calculator</em></strong> inner sınıfını oluşturuyoruz. Ve içerisine iki sayının toplamını döndüren <strong><em>add() </em></strong>metodunu yazıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fab1a29dd13956044d20c73729cf0748/href">https://medium.com/media/fab1a29dd13956044d20c73729cf0748/href</a></iframe><p>Şimdi bu sınıf için <strong><em>test_add()</em></strong> metodunu yazalım. Test metodlarımızı <strong><em>BDD(Behaviour driven development)</em></strong> yaklaşımıyla yazıyoruz. Bu yaklaşımı <em>given</em>, <em>when </em>ve <em>then </em>bölümleri olarak söyleyebiliriz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03df1ec2cb944dcc0bf128f6adbd5695/href">https://medium.com/media/03df1ec2cb944dcc0bf128f6adbd5695/href</a></iframe><ul><li><strong>given — </strong>bu senaryoda test edeceğimiz davranışa başlamadan önce <em>değişkenlerin değerleri</em>. Bunu testin ön koşulları olarak düşünebilirsiniz.</li><li><strong>when — </strong>test edeceğimiz davranış. Yani test edeceğimiz metodu bu bölümde çalıştırıyoruz.</li><li><strong>then — </strong>test edeceğimiz davranış nedeniyle beklediklerimiz. Test ettiğimiz metoddan hangi sonuçları beklediğimizi burada yazıyoruz.</li></ul><p><strong><em>Test metodunda, Calculator sınıfının add(a, b) metoduna 10 ve 20 parametrelerini girdiğimizde 30 sonucunun dönmesini beklediğimizi söyledik. </em></strong>Testi run ettiğinizde aşağıdaki sonucu alacaksınız.</p><p>Her şey yeşil olduğuna göre testimiz geçti !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*L2q_R7qhAdLbd-Ol8_65EA.jpeg" /></figure><p><strong><em>Expected</em></strong> değerini farklı bir değer vererek testin <strong><em>fail </em></strong>durumunu gözlemleyebilirsiniz. Ben burada yazıyı uzatıp vaktinizi almamak adına eklemedim.</p><h4>Unit Testlerde İsimlendirme</h4><p>Bu konuda farklı isimlendirme tipleri bulunuyor. Bu yazıda bootcamp eğitiminde öğrendiğim isimlendirme yöntemini aktaracağım.</p><pre>@Test<br>public void <strong>should_returnEquals_when_addTwoNumber()</strong>{</pre><pre>}</pre><p>Burada <strong><em>should</em></strong> ve <strong><em>when</em></strong> prefixlerimiz. Yani bunları her zaman koyuyoruz. Diğer kısımlar ise metodumuza göre değişiyor. Test metodunu okuduğumuzda, o testin ne için yapıldığını çıkarabilmeliyiz. Metodun daha kolay okunması adına alt tireler kullanıyoruz.</p><p>Test metodumuzu şu şekilde okuyabiliriz: <strong><em>İki sayı birbirine eklendiğinde bunlar eşit olmalı.</em></strong></p><h4>Worst Case İçin Test Yazmak</h4><p>Yukarıda best case senaryosu için test metodu geliştirdik. Bunun tersi durumla da karşılaşabiliriz. İki sayı toplandığında birbirine eşit olmadığı durumları da test etmemiz gerekiyor.</p><p>Şimdi aynı örnek için olumsuz durumu yazalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a8e080048bd9a812daf138f66c2de9e/href">https://medium.com/media/2a8e080048bd9a812daf138f66c2de9e/href</a></iframe><p>Çalıştırdığınızda yine testin geçtiğini göreceksiniz. <strong><em>Burada test metodumuza 10 ve 20 sayılarının toplamının 40&#39;a eşit olmamasını beklediğimizi söyledik.</em></strong> Nitekim 40&#39;a eşit değil ve testimiz geçti.</p><h4>Bazı Temel Noktalar</h4><ul><li>Test sınıfının içindeki tüm testleri aynı anda koşmak isterseniz sınıfın solundaki <strong>run </strong>komutunu çalıştırmalısınız.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*WfBEHH3L4oOhME3TCVpeDQ.jpeg" /></figure><ul><li><strong>DisplayName() — </strong>Metod ismini değiştirmek için kullanılıyor.</li></ul><pre>@Test<br><strong>@DisplayName(value = &quot;This test should return equals when add two number&quot;)</strong><br>public void should_returnEquals_when_addTwoNumber(){<br>   <br>   ...</pre><pre>}</pre><ul><li><strong>RepeatedTest() — </strong>Aynı testi tekrarlı olarak girilen parametre değeri kadar koşar.</li></ul><pre>@Test<br><strong>@RepeatedTest(10)</strong><br>public void should_returnNotEquals_when_addTwoNumber(){</pre><pre>}</pre><ul><li><strong>ParameterizedTest()<em> — </em></strong>Aynı testi, birden fazla değer ile koşturmak için kullanılıyor.</li></ul><p><em>Örnek üzerinden incelemek için y</em>eni bir test metodu yazıyoruz. <strong><em>Bir sayıyı 0 ile çarptığımızda sonucunun 0 dönmesini bekliyoruz.</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5aa45f1972a288d96127174bcf6d76e/href">https://medium.com/media/a5aa45f1972a288d96127174bcf6d76e/href</a></iframe><p>Yukarıda değerlerimizi <strong><em>ValueSource()</em></strong> ile girdik. Bununla beraber birden fazla değer girmek için <strong><em>CsvSource()</em></strong> anotasyonu kullanılıyor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7d1b55721eac8aed015379a520dd218/href">https://medium.com/media/c7d1b55721eac8aed015379a520dd218/href</a></iframe><h4>Hata Durumlarının Test Edilmesi</h4><p>Bunun için <strong><em>Executable </em></strong><em>kullanılıyor. </em><strong><em>JUnit 5</em></strong> ile beraber ile gelen güzel bir özellik. Executable interface i içerisine hatayı sarmallıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc58aac237129a8d0ccea96b2ff83efa/href">https://medium.com/media/cc58aac237129a8d0ccea96b2ff83efa/href</a></iframe><p>Yukarıdaki örnek kodun son satırını(then), yorum satırına alarak fırlattığı hatayı görebilirsiniz.<em> </em><strong><em>“java.lang.ArithmeticException: / by zero”</em></strong> hatasını alıyor olacaktık. Executable ile bu hatayı sarmalladık ve assertThrows ile fırlatıldığını kontrol ettik.</p><blockquote>assertThrows()’un birinci parametresine test edeceğimiz hata türünü yazıyoruz.</blockquote><ul><li><strong>BeforeEach — </strong>Her test metodundan önce çalışır. Bir değişkenin initialize edilmesi gibi durumları burada yapabiliriz.</li></ul><p>Burada <em>calculatorTest </em>nesnemizi oluşturma işlemini <em>setup()</em> metodunda gerçekleştirdik.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36575a6f470a188df3de35931fd4f781/href">https://medium.com/media/36575a6f470a188df3de35931fd4f781/href</a></iframe><ul><li><strong>AfterEach — </strong>Her bir test sonrası yapılacak işlemler için kullanılıyor. Çok sık kullanılmayan bir anotasyon.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ced2914a25e6dc31efea4e0b5366d549/href">https://medium.com/media/ced2914a25e6dc31efea4e0b5366d549/href</a></iframe><ul><li><strong>BeforeAll — </strong>Tüm testlerden önce koşulur. Statik olarak tanımlanır. Örneğin data source ve dosya işlemleri gibi.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0293e5eb875af01e971ca7dca90f46ce/href">https://medium.com/media/0293e5eb875af01e971ca7dca90f46ce/href</a></iframe><ul><li><strong>AfterAll — </strong>Tüm testlerden sonra kaynakları boşaltmak için kullanılıyor. Statik olarak tanımlanır. Bu iki anotasyon özellikle entegrasyon testleri için kullanışlı olabilir.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f87f20c4e94ee11744f1663817e2b14/href">https://medium.com/media/5f87f20c4e94ee11744f1663817e2b14/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*SCIUsLq_5nSwKtyLbdOXYQ.jpeg" /></figure><h3>Controller ve Service Sınıflarına Birim Testi Yazmak</h3><p>Kodlarımızı yazarken ne kadar çok şişkin metod olursa (yani mümkün olduğunca az satırda işi bitirmekten öte çok uzun implementasyona sahip bir metodumuz olursa) onun unit testini yazmak zorlaşır. Ne kadar minimal metodlar olursa unit testini yazmak kolaylaşır.</p><p>Controller ve Service testlerine geçmeden önce çok kısa TDD yani test driven development konusuna değinmek istiyorum. <strong><em>Bu yaklaşımda ilk olarak testi ardından kodu yazıyoruz.</em></strong> Bu yazıda amacım nasıl unit test yazıldığına genel hatlarıyla değinmek. Bu yüzden örnek çalışmada TDD yaklaşımını kullanmayacağım. Sadece bilgi vermek amaçlı bahsetmek istedim. Daha detaylı bilgi için <a href="https://www.youtube.com/watch?v=s9vt6UJiHg4"><strong><em>şu</em></strong></a> ve <a href="https://www.youtube.com/watch?v=z6gOPonp2t0"><strong><em>şu videolar</em></strong></a><strong><em>ı </em></strong>izlemenizi tavsiye ederim.</p><h3>Case</h3><p><strong><em>localhost:8080/api/v1/customers</em></strong> adresinde yayınladığımız bir restfull apimiz var. Müşteri ekleme, listeleme ve silme işlemlerini gerçekleştiriyor.</p><h3>Controller Testi</h3><p><em>CustomerController</em> sınıfı içerisindeyken <strong><em>Ctrl+Shift+T</em></strong> ‘ye basın. <strong><em>src/test/ controllers</em></strong> klasörü altına <em>CustomerControllerTest</em> sınıfı oluşacak. Test metodlarımızı bu sınıfın içerisine yazıyor olacağız.</p><h4>create() Metodu Best Case İçin Test</h4><p>İlk olarak create metodu için test yazalım. Dikkat ettiyseniz bu metod içerisinde dışarıdan <em>CustomerService</em> sınıfını kullanıyoruz. Bu bizim için bir zorluk anlamına geliyor. Çünkü birim testinde dışarıdaki her şeyden bağımsız sadece metodumuzun doğru şekilde çalışıp çalışmadığına bakıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2afcfd11ce914763396008b6b433c1e6/href">https://medium.com/media/2afcfd11ce914763396008b6b433c1e6/href</a></iframe><p>Bu noktada yapmamız gereken servise doğrudan gitmeden <strong><em>customerService.create(request)</em></strong> ile dönen değeri taklit etmek yani mocklamak. Bunun içinde Spring’in içerisinde hazır gelen <strong><em>Mockito</em></strong>’yu kullanacağız.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5116ba339509971dd29c12dd6dc8525/href">https://medium.com/media/b5116ba339509971dd29c12dd6dc8525/href</a></iframe><ul><li><strong><em>@ExtendWith(MockitoExtension.class) — </em></strong>Test sınıfları için kullanılan anotasyon. (Mockito’yu kullanacağımızı söyledik.)</li><li><strong><em>@Mock</em> — </strong>Test edeceğimiz sınıfın bağımlılıklarını mocklamak yani taklit etmek için kullanılan anotasyon.</li><li><strong><em>@InjectMocks</em> — </strong>Mock nesnelerini test edeceğimiz sınıfa inject etmek için kullanılıyor.</li><li><strong><em>@Test </em>— </strong>Test metodları için kullanılan anotasyon.</li></ul><p>Artık testimizi yazabiliriz ! 💪</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c5e7575f416da128f0a16eb7640f7eb/href">https://medium.com/media/6c5e7575f416da128f0a16eb7640f7eb/href</a></iframe><p>Aşağıdaki kod satırında(8. satır), test metodumuza <strong><em>mockCustomerService.create()</em></strong> çağrıldığında <strong><em>expected</em></strong> değişkenini dönmesini söylüyoruz. Burada mock işlemimizi gerçekleştirmiş olduk.</p><ul><li><strong><em>when() </em>—</strong> Hangi metodun çağrılacağını burada belirtiyoruz.</li><li><strong><em>thenReturn() — </em></strong>Çağrılan metodun hangi sonucunu dönmesini beklediğimizi burada belirtiyoruz.</li><li><strong><em>any() </em>— </strong>Obje tipinde<strong> </strong>herhangi bir parametre alabileceğini belirttik.</li></ul><pre><strong><em>when</em>(mockCustomerService.create(<em>any</em>())).thenReturn(expected);</strong></pre><p>11–13. satırlarda create metodumuzu test ediyoruz ve dönen sonucu <strong><em>actual</em></strong> değişkenine atıyoruz.</p><p>16. satırdan itibaren ise dönen ve beklediğimiz sonuçları karşılaştırıyoruz.</p><pre><em>assertAll</em>(<br>        () -&gt; <em>assertNotNull</em>(actual),<br>        () -&gt; <em>assertEquals</em>(HttpStatus.<em>CREATED</em>, response.getStatusCode()),<br>        () -&gt; <em>assertEquals</em>(expected.get(), actual),<br>        () -&gt; <em>assertEquals</em>(customer.getIdentificationNumber(), actual.getIdentificationNumber()));</pre><ul><li><strong><em>assertNotNull(actual) — </em></strong><em>A</em>ssert iddia etmek anlamına geliyor. Burada parametre olarak geçtiğimiz <strong><em>actual</em></strong> değişkeninin <strong><em>null</em></strong> olmayacağını iddia ediyoruz. Eğer actual değişkeni null değilse true dönecektir.</li><li><strong><em>assertEquals(param1, param2) — </em></strong>Her iki parametrenin birbirine eşit olmasını karşılaştırıyoruz.</li></ul><p>Soldaki yeşil <strong><em>run</em></strong> butonuna tıklayıp çalıştıralım. Testimiz geçti!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*HLNrDSY4rRVNmLnpsbkRfw.jpeg" /></figure><h4>create() Metodu Worst Case İçin Test</h4><p>Şimdi de create metodunun hata aldığı durumu test edelim. Hatırlarsanız controller’da <em>mockCustomerService.create()</em> metodundan <strong><em>null</em></strong> dönmesi durumunda <em>HttpStatus.BAD_REQUEST döndürüyorduk. Bunu test etmek için 4. satırda thenReturn()’e </em><strong><em>null</em></strong><em> değere sahip </em><strong><em>Optional</em></strong><em> nesnesi geçtik.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db91885a2ff9bbd5269d86779c0cbf66/href">https://medium.com/media/db91885a2ff9bbd5269d86779c0cbf66/href</a></iframe><h4>getAll() ve getById() Metodlarının Test Edilmesi</h4><p>Bu metodlar için yine aynı işlemler tekrar ettiği için burada yer vermedim. <a href="https://github.com/betul-sahin/spring-boot-unit-test"><em>Şu repodan</em></a> tamamına ulaşabilirsiniz.</p><h4>deleteById() Metodunun Test Edilmesi</h4><p>Yine bu metod için de standart işlemler tekrarlanıyor. Burada worst case’e yer vermek istedim.</p><p>Controller sınfına gidelim. Müşteri varsa silip return değerimiz <strong><em>void</em></strong> olduğu için <em>HttpStatus.NO_CONTENT</em> döndürüyoruz. Müşteri bulunamadıysa <em>HttpStatus.NOT_FOUND döndürüyoruz.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18040d7ee8266c6b82ab5cdf322214ff/href">https://medium.com/media/18040d7ee8266c6b82ab5cdf322214ff/href</a></iframe><p>Şimdi müşteri bulunamadı durumu için aşağıdaki test metodunu yazalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/331920bc8a9a9afe3510b29a9cf9491a/href">https://medium.com/media/331920bc8a9a9afe3510b29a9cf9491a/href</a></iframe><p>4. satırı inceleyelim.</p><ul><li><strong><em>doThrow(param) — </em></strong><em>buraya fırlatılacak hata sınıfını belirtiyoruz.</em></li><li><strong><em>when(param).deleteById(anyLong()) — </em></strong>burada servis nesnemizin <em>deleteById()</em> metodunu çağıracağımızı belirtiyoruz. Dikkat ettiyseniz öncekinden farklı olarak nokta ile ayırarak yazdık. Bunun sebebi metodun <strong><em>void</em></strong> dönmesi.</li></ul><h3>Service Testi</h3><p>Servis testlerinde de benzer işlemler yapılmaktadır. Dilerseniz aşağıdaki repodan inceleyebilirsiniz.</p><p>Umarım faydalı olmuştur. Tüm kaynak kodlara <strong>ş</strong><a href="https://github.com/betul-sahin/spring-boot-unit-test"><strong><em>u repodan</em></strong></a> ulaşabilirsiniz.</p><p>Keep coding ! 🚀</p><h3>Referans Kaynaklar</h3><ul><li><a href="https://junit.org/junit5/docs/current/user-guide/">JUnit 5 User Guide</a></li><li><a href="https://tr.wikipedia.org/wiki/Birim_testi">Birim testi - Vikipedi</a></li><li><a href="https://github.com/betul-sahin/spring-boot-unit-test">GitHub - betul-sahin/spring-boot-unit-test</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fs9vt6UJiHg4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Ds9vt6UJiHg4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fs9vt6UJiHg4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c376cf1f8929699d158e941e90c9a487/href">https://medium.com/media/c376cf1f8929699d158e941e90c9a487/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fz6gOPonp2t0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dz6gOPonp2t0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fz6gOPonp2t0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef523a52a803e95b7a2411e3891fd670/href">https://medium.com/media/ef523a52a803e95b7a2411e3891fd670/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1e4fc1f3df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Unit Tests in Spring Boot]]></title>
            <link>https://betulsahinn.medium.com/writing-unit-tests-in-spring-boot-cd0a58df53cc?source=rss-c720cfe5ef8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd0a58df53cc</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[junit-5]]></category>
            <dc:creator><![CDATA[Betül Şahin]]></dc:creator>
            <pubDate>Sun, 02 Jan 2022 20:00:44 GMT</pubDate>
            <atom:updated>2022-01-02T21:48:38.316Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we’ll talk about <strong><em>writing unit tests</em></strong> in Spring Boot applications. At the beginning we will give a basic introduction to the concept of testing. Then we will talk about how to write unit tests for Controller and Service classes.</p><p><em>Here, I shared what I learned in the </em><a href="https://www.patika.dev/programlar/gittigidiyor-java-spring-bootcamp"><em>Java &amp; Spring Framework Bootcamp</em></a><em> organized in collaboration with </em><a href="https://www.gittigidiyor.com/"><em>GittiGidiyor</em></a><em> — </em><a href="https://www.kodluyoruz.org/"><em>Kodluyoruz</em></a><em> &amp; </em><a href="https://www.patika.dev/"><em>Patika.dev</em></a><em>, which I attended this summer as a student.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8x2WsIxdqHcIrCn7MjfPww.jpeg" /></figure><h3>What is Unit Test ?</h3><p>Writing unit tests is an important issue that is the responsibility of the developer of the application.</p><p><strong><em>Wikipedia</em></strong> defines <a href="https://en.wikipedia.org/wiki/Unit_testing"><em>unit tests</em></a> as</p><blockquote><em>In </em><a href="https://en.wikipedia.org/wiki/Computer_programming"><em>computer programming</em></a><em>, </em><strong><em>unit testing</em></strong><em> is a </em><a href="https://en.wikipedia.org/wiki/Software_testing"><em>software testing</em></a><em> method by which individual units of </em><a href="https://en.wikipedia.org/wiki/Source_code"><em>source code</em></a><em> — sets of one or more computer program </em><a href="https://en.wikipedia.org/wiki/Modular_programming"><em>modules</em></a><em> together with associated control data, usage </em><a href="https://en.wikipedia.org/wiki/Procedure_(computer_science)"><em>procedures</em></a><em>, and operating procedures — are tested to determine whether they are fit for use.</em></blockquote><p>There are some of the different kind of tests such as <strong><em>unit testing</em></strong> and <strong><em>integration testing</em></strong>. However, integration testing is not recommended unless it is very necessary. These are tests that have the risk of exploding the system at some point.</p><h3>How to Write a Test Method ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/0*5WoZZkluPpoVVf1A.jpeg" /></figure><p>We write our tests under the <strong><em>src/test</em></strong> folder. Directory structure guides us in this regard.</p><p>Here we create the <strong>SampleUnitTestClass </strong>class.</p><p>First, let’s create a test method as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9842d3b6633ed33424ef6ad3d0676ae3/href">https://medium.com/media/9842d3b6633ed33424ef6ad3d0676ae3/href</a></iframe><ul><li><strong>void — </strong>Test methods are always written as void. Because we don’t call test methods anywhere. This means that all unit tests are independent of each other.</li><li><strong>@Test — </strong>We always put this annotation at the beginning of our test methods. It is in the package <strong><em>org.junit.jupiter.api</em></strong>. Spring provides the <strong><em>JUnit</em></strong> library by default. JUnit allows us to write unit tests. <strong><em>JUnit 5</em></strong> was released along with Java 8.</li></ul><p><em>To run test, click the </em><strong><em>run </em></strong><em>button to the left of the method. You will get the following output. The test result is in the lower right section.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*RpQbfQT10jUZnDNw.jpeg" /></figure><p><strong>So let’s start ! </strong>💪</p><p>Create <strong><em>Calculator</em></strong> inner class inside <strong><em>SampleUnitTestClass</em></strong> class. And then write <strong><em>add()</em></strong> method which returns the sum of two numbers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fab1a29dd13956044d20c73729cf0748/href">https://medium.com/media/fab1a29dd13956044d20c73729cf0748/href</a></iframe><p>Now let’s write the <strong><em>test_add()</em></strong> method for this class. Test methods are written with the BDD (Behavior driven development) approach. This approach consists of <strong><em>given</em></strong>, <strong><em>when </em></strong>and <strong><em>then </em></strong>parts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03df1ec2cb944dcc0bf128f6adbd5695/href">https://medium.com/media/03df1ec2cb944dcc0bf128f6adbd5695/href</a></iframe><ul><li><strong>given — </strong>the prerequisites for the test.</li><li><strong>when — </strong>the behavior that you’re specifying.</li><li><strong>then — </strong>describes the changes you expect due to the specified behavior.</li></ul><p>In the test method, <strong><em>we said that when we give the parameters 10 and 20 in the add(a, b) method of the Calculator class, we expect the result of 30. </em></strong>When you run the test you will get the following result.</p><p>As you see everything is green, our test passed!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Irly1Prxpyn_yZpq.jpeg" /></figure><p>You can observe the fail status of the test by setting the <strong><em>Expected </em></strong>value to a different value. I don’t want to prolong the article and take up your time.</p><h3>Unit Test Naming Conventions</h3><p>There are different types of naming conventions. In this tutorial, i shared what i learned in the bootcamp training.</p><pre>@Test<br>public void <strong>should_returnEquals_when_addTwoNumber()</strong>{}</pre><p>Here are the <strong><em>should</em></strong> and <strong><em>when</em></strong> prefixes. So we always put them in. Other parts are changing according to our method. When we read the test method, we should be understand what that test is for. We use underscores to make the method easier to read.</p><p>We can read our test method as follows: <strong><em>When two numbers are added together, they must be equal.</em></strong></p><h3>Worst Case Test</h3><p>Above, we developed a test method for the best case scenario. We may encounter the opposite situation. We also need to test for cases where two numbers are not equal when added.</p><p>Now let’s write the negative case for the same example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a8e080048bd9a812daf138f66c2de9e/href">https://medium.com/media/2a8e080048bd9a812daf138f66c2de9e/href</a></iframe><p>When you run it, you will see that the test passed. Here <strong><em>we said that we expect the sum of the numbers 10 and 20 not to equal 40</em></strong>. As a matter of fact, it does not equal 40 and our test passed.</p><h3>The Basics of Unit Testing</h3><ul><li>If you want to run all the tests inside the test class at the same time, you should run the run command on the left of the class.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*c2oTj3AG1F6Z-0yp.jpeg" /></figure><ul><li><strong>DisplayName() — </strong>Used to change method name.</li></ul><pre>@Test<br><strong>@DisplayName(value = &quot;This test should return equals when add two number&quot;)</strong><br>public void should_returnEquals_when_addTwoNumber(){<br>   <br>   ...}</pre><ul><li><strong>RepeatedTest() — </strong>Runs the same test as many times as the given parameter value.</li></ul><pre>@Test<br><strong>@RepeatedTest(10)</strong><br>public void should_returnNotEquals_when_addTwoNumber(){}</pre><ul><li><strong>ParameterizedTest() — </strong>Used to run the same test with more than one value.</li></ul><p><em>Write a new test method to examine through the example. </em><strong><em>When we multiply a number by 0, we expect the result to return 0</em></strong><em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5aa45f1972a288d96127174bcf6d76e/href">https://medium.com/media/a5aa45f1972a288d96127174bcf6d76e/href</a></iframe><p>Above, we given our values with <strong>ValueSource()</strong>. However, the <strong>CsvSource()</strong> annotation is used to give multiple values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7d1b55721eac8aed015379a520dd218/href">https://medium.com/media/c7d1b55721eac8aed015379a520dd218/href</a></iframe><h3>Testing Error Conditions</h3><p><strong><em>Executable </em></strong>is used for this. It’s a nice feature that released with <strong><em>JUnit 5</em></strong>. We wrap the error in the Executable interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc58aac237129a8d0ccea96b2ff83efa/href">https://medium.com/media/cc58aac237129a8d0ccea96b2ff83efa/href</a></iframe><p>We would be getting the error <strong>“java.lang.ArithmeticException: / by zero”</strong>.</p><blockquote><em>In the first parameter of assertThrows() we specify the type of error to test.</em></blockquote><ul><li><strong>BeforeEach — </strong>Runs before each test method. Here we can do situations like initializing a variable.</li></ul><p>We created our <em>calculatorTest</em> object in the <em>setup()</em> method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36575a6f470a188df3de35931fd4f781/href">https://medium.com/media/36575a6f470a188df3de35931fd4f781/href</a></iframe><ul><li><strong>AfterEach — </strong>It is used for operations after each test. An annotation that is not used very often.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ced2914a25e6dc31efea4e0b5366d549/href">https://medium.com/media/ced2914a25e6dc31efea4e0b5366d549/href</a></iframe><ul><li><strong>BeforeAll — </strong>Run before all tests. It is defined as static.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0293e5eb875af01e971ca7dca90f46ce/href">https://medium.com/media/0293e5eb875af01e971ca7dca90f46ce/href</a></iframe><ul><li><strong>AfterAll — </strong>Used to free up resources after all tests. It is defined as static. These two annotations can be especially useful for integration tests.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f87f20c4e94ee11744f1663817e2b14/href">https://medium.com/media/5f87f20c4e94ee11744f1663817e2b14/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*4_uEyHrff025YIYm.jpeg" /></figure><h3>Unit Testing for Controller and Service Layer</h3><p>It is hard to write a unit test for fat methods. However it is easy to write a unit test for a more minimal methods.</p><p>First of all, I would like to briefly touch on TDD, namely test driven development. In this approach, we write the test first and then the code. In this post, my aim is to give an overview of how to write a unit test. So I will not use the TDD approach in the case study. I just wanted to mention it for giving information about it. For more detailed information, I recommend you to watch <a href="https://www.youtube.com/watch?v=s9vt6UJiHg4"><strong><em>this</em></strong></a> and<a href="https://www.youtube.com/watch?v=z6gOPonp2t0"><strong><em> that</em></strong></a> videos.</p><h3>Case</h3><p>We have a restfull api that we publish at <strong><em>localhost:8080/api/v1/customers</em></strong>. It performs customer addition, listing and deletion operations.</p><h3>Testing The Controller Layer</h3><p>Press <strong><em>Ctrl+Shift+T</em></strong> while inside the <em>CustomerController</em> class. The <strong><em>CustomerControllerTest</em></strong> class will be created under the <em>src/test/controllers</em> folder.</p><h4>Testing for Best Case of create() Method</h4><p>First, let’s write a test for the create method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2afcfd11ce914763396008b6b433c1e6/href">https://medium.com/media/2afcfd11ce914763396008b6b433c1e6/href</a></iframe><p>Then we will mock the return value of <strong><em>customerService.create(request)</em></strong>. For this, we will use <strong><em>Mockito</em></strong> library that comes ready in Spring.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5116ba339509971dd29c12dd6dc8525/href">https://medium.com/media/b5116ba339509971dd29c12dd6dc8525/href</a></iframe><ul><li><strong><em>@ExtendWith(MockitoExtension.class) — </em></strong>The annotation used for test classes.</li><li><strong><em>@Mock</em> — </strong>The annotation used to mock the dependencies of the test class.</li><li><strong><em>@InjectMocks</em> — </strong>The annotation used to inject mock objects into the test class.</li><li><strong><em>@Test </em>— </strong>The annotation used for test methods.</li></ul><p>Now we can write our test ! 💪</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c5e7575f416da128f0a16eb7640f7eb/href">https://medium.com/media/6c5e7575f416da128f0a16eb7640f7eb/href</a></iframe><p>In the following line of code (line 8), we are telling our test method to return the <strong><em>expected</em></strong> variable when <strong><em>mockCustomerService.create()</em></strong> is called. Thus, we have done the mock process.</p><ul><li><strong><em>when() </em>— </strong>We specify which method to call.</li><li><strong><em>thenReturn() —</em></strong>We specify what result we expect the called method to return.</li><li><strong><em>any() </em>— </strong>We specify that it can take any parameter of object type.</li></ul><pre><strong><em>when</em>(mockCustomerService.create(<em>any</em>())).thenReturn(expected);</strong></pre><p>We test our <strong><em>create</em></strong> method on the 11–13. lines. And then we assign the returned result to the variable of the <strong><em>actual</em></strong>.</p><p>From the 16th line, we compare the returned and the expected results.</p><pre><em>assertAll</em>(<br>        () -&gt; <em>assertNotNull</em>(actual),<br>        () -&gt; <em>assertEquals</em>(HttpStatus.<em>CREATED</em>, response.getStatusCode()),<br>        () -&gt; <em>assertEquals</em>(expected.get(), actual),<br>        () -&gt; <em>assertEquals</em>(customer.getIdentificationNumber(), actual.getIdentificationNumber()));</pre><ul><li><strong><em>assertNotNull(actual) — </em></strong>We claim that the variable of actual will not be null. It will return <strong><em>true</em></strong> if the variable of actual is not null.</li><li><strong><em>assertEquals(param1, param2) — </em></strong>We compare whether both parameters are equal to each other.</li></ul><p>Let’s click the green run button on the left to run it. Our test passed!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*HLNrDSY4rRVNmLnpsbkRfw.jpeg" /></figure><h4>Testing for Worst Case of create() Method</h4><p>Now let’s test the worst case of the create method. For this, we passed a nullable Optional object to thenReturn() on line 4.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db91885a2ff9bbd5269d86779c0cbf66/href">https://medium.com/media/db91885a2ff9bbd5269d86779c0cbf66/href</a></iframe><h4>Testing for getAll() ve getById() Methods</h4><p>You can access the test codes for these methods from <a href="https://github.com/betul-sahin/spring-boot-unit-test"><strong><em>this repository.</em></strong></a></p><h4>Testing for deleteById() Method</h4><p>Let’s test the worst case of the deleteById() method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/331920bc8a9a9afe3510b29a9cf9491a/href">https://medium.com/media/331920bc8a9a9afe3510b29a9cf9491a/href</a></iframe><p>Let’s look 4th line.</p><ul><li><strong><em>doThrow(param) —</em></strong>We specify the exception class to throw.</li><li><strong><em>when(param).deleteById(anyLong()) — </em></strong>We specify that we will call the deleteById() method of our service object.</li></ul><h3>Testing The Service Layer</h3><p>There are similar procedures in service tests. You can checkout it from the repository below.</p><p>I hope it was useful for you. You can access the whole project from <a href="https://github.com/betul-sahin/spring-boot-unit-test"><strong><em>this repository.</em></strong></a></p><p>Keep coding ! 🚀</p><h3>Reference Resources</h3><ul><li><a href="https://en.wikipedia.org/wiki/Unit_testing">Unit testing - Wikipedia</a></li><li><a href="https://junit.org/junit5/docs/current/user-guide/">JUnit 5 User Guide</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fs9vt6UJiHg4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Ds9vt6UJiHg4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fs9vt6UJiHg4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c376cf1f8929699d158e941e90c9a487/href">https://medium.com/media/c376cf1f8929699d158e941e90c9a487/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fz6gOPonp2t0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dz6gOPonp2t0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fz6gOPonp2t0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef523a52a803e95b7a2411e3891fd670/href">https://medium.com/media/ef523a52a803e95b7a2411e3891fd670/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd0a58df53cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why is @Autowired annotation not recommended ?]]></title>
            <link>https://betulsahinn.medium.com/why-is-autowired-annotation-not-recommended-4939c46da1f8?source=rss-c720cfe5ef8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4939c46da1f8</guid>
            <category><![CDATA[autowired]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[inversion-of-control]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-ioc]]></category>
            <dc:creator><![CDATA[Betül Şahin]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 17:45:25 GMT</pubDate>
            <atom:updated>2021-12-31T05:54:10.930Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why is @Autowired annotation not recommended ?</h3><p>In this post, I will explain <strong><em>why Autowired annotation is not recommended</em></strong>. I will clarify this question as simply as possible and through examples.</p><p>I hope you can answer very well when you come across it :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDwtUY1Zq431TQFsPQ11kQ.jpeg" /></figure><p>As you know, <strong><em>Autowired</em></strong> annotation is used <strong><em>to inject dependencies</em></strong>. You can find a usage example below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a5569d1ccbe1fa65fd3ccffc33d9ff9/href">https://medium.com/media/1a5569d1ccbe1fa65fd3ccffc33d9ff9/href</a></iframe><p>At this point, let’s talk about <strong><em>the dependency injection</em></strong> technique first. Then let’s talk about how it is implemented in <strong><em>the Spring Framework</em></strong>. Next, let’s see the reasons why <strong><em>Autowired annotation</em></strong>, which is a <strong><em>setter injection</em></strong> method, is not recommended.</p><h3>Spring IOC Container</h3><p>Spring Framework adopts <strong><em>Program to Interface</em></strong> approach. In this approach, dependencies between classes are provided through <strong><em>interfaces</em></strong> and <strong><em>abstract classes</em></strong>.</p><p><strong><em>IOC(Inversion of Control)</em></strong> is a principle that provides modularity. It takes control from the developer and hands it over to another actor, such as the framework. When we hand over control to the framework, we provide <strong><em>loosely coupling</em></strong>. That is, we minimize dependencies when creating an object.</p><p>Now let’s talk about Spring Framework…</p><p>As developers we are responsible for creating java objects. This responsibility is passed to <strong><em>Spring IOC Container</em></strong>. Spring IOC Container, also called <strong><em>Application context</em></strong>, is responsible for instantiating java objects known as beans to be created with appropriate parameters and configurations when needed.</p><blockquote>The object doesn’t know the concrete classes to which the dependencies are provided.</blockquote><p>There are many ways to implement the IOC as you will see in the image below. <strong><em>Dependency injection</em></strong> is one of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/0*AbUJKzAm70cW20K6.png" /><figcaption>www.splessons.com</figcaption></figure><h4>Dependency Injection</h4><p>It is a technique in software engineering where the dependencies of another object are provided through an object.</p><p>Dependency injection is implemented with 3 different methods.</p><ul><li>Constructor Injection (recommended method)</li><li>Setter Injection (Property Injection)</li><li>Method Injection</li></ul><p>The subject of the article and the recommended method is <strong><em>constructor injection</em></strong>. You can find a usage example below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a7edddc4a4656039ca3c7216c392986/href">https://medium.com/media/1a7edddc4a4656039ca3c7216c392986/href</a></iframe><h4>Why Constructor Injection ?</h4><ul><li><strong>Testability — </strong>Prevents NullPointer Exception. In testing, it’s easy to pass mock objects to the constructor.</li></ul><p>If we had used Autowired, we would have been getting the following error in the test. Therefore, it is not recommended to use Autowired.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*BVSjlYNF4_RQgG1w.jpeg" /></figure><ul><li><strong>Safety — </strong>Forces Spring to provide mandatory dependencies. We make sure that the created objects are valid after construction.</li><li><strong>Readability — </strong>Dependencies passed as parameters to the constructor are mandatory. Dependencies provided by the Property or setter injection method are optional.</li></ul><p>Finally, I leave it for <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-dependencies"><strong><em>those</em></strong></a> who want to read the Spring team’s explanation on this subject.</p><blockquote><em>Constructor-based or setter-based DI?</em></blockquote><blockquote><em>Since you can mix constructor-based and setter-based DI, it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies. Note that use of the </em><a href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-required-annotation"><em>@Required</em></a><em> annotation on a setter method can be used to make the property be a required dependency; however, constructor injection with programmatic validation of arguments is preferable.</em></blockquote><blockquote><em>The Spring team generally advocates constructor injection, as it lets you implement application components as immutable objects and ensures that required dependencies are not </em><em>null. Furthermore, constructor-injected components are always returned to the client (calling) code in a fully initialized state. As a side note, a large number of constructor arguments is a bad code smell, implying that the class likely has too many responsibilities and should be refactored to better address proper separation of concerns.</em></blockquote><blockquote><em>Setter injection should primarily only be used for optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency. One benefit of setter injection is that setter methods make objects of that class amenable to reconfiguration or re-injection later. Management through </em><a href="https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#jmx"><em>JMX MBeans</em></a><em> is therefore a compelling use case for setter injection.</em></blockquote><blockquote><em>Use the DI style that makes the most sense for a particular class. Sometimes, when dealing with third-party classes for which you do not have the source, the choice is made for you. For example, if a third-party class does not expose any setter methods, then constructor injection may be the only available form of DI.</em></blockquote><p>I hope it was useful for you. You can access the source codes from <a href="https://github.com/betul-sahin/spring-boot-dependency-injection"><strong><em>this repo</em></strong></a>.</p><p>Keep coding ! 🚀</p><h4>Reference Resources</h4><ul><li><a href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-dependencies">Core Technologies</a></li><li><a href="https://github.com/betul-sahin/spring-boot-dependency-injection">GitHub - betul-sahin/spring-boot-dependency-injection: Neden Autowired kullanılması önerilmiyor ? Constructor Injection Avantajları</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4939c46da1f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neden Autowired kullanılması önerilmiyor ? Constructor Injection Avantajları]]></title>
            <link>https://betulsahinn.medium.com/neden-autowired-kullan%C4%B1lmas%C4%B1-%C3%B6nerilmiyor-constructor-injection-avantajlar%C4%B1-36b712523932?source=rss-c720cfe5ef8------2</link>
            <guid isPermaLink="false">https://medium.com/p/36b712523932</guid>
            <category><![CDATA[constructor-injection]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[spring-ioc]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Betül Şahin]]></dc:creator>
            <pubDate>Fri, 17 Dec 2021 08:26:45 GMT</pubDate>
            <atom:updated>2021-12-24T16:34:30.963Z</atom:updated>
            <content:encoded><![CDATA[<h3>Neden @Autowired kullanılması önerilmiyor? Constructor Injection Avantajları</h3><p>Bu yazıda <strong><em>neden Autowired anotasyonu kullanılması önerilmiyor</em></strong> konusunu aktarmaya çalışacağım. Mülakatlarda sıkça karşılaşılan bu soruyu olabildiğince yalın bir şekilde ve örnekler üzerinden açıklamaya çalışacağım.</p><p>Umarım karşınıza çıktığında güzel bir şekilde cevaplamanıza vesile olabilirim :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDwtUY1Zq431TQFsPQ11kQ.jpeg" /></figure><p>Bildiğiniz gibi <strong><em>Autowired </em></strong>anotasyonu <strong><em>bağımlılık inject</em></strong> etmek için kullanılıyor. Aşağıda kullanım örneğini bulabilirsiniz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a5569d1ccbe1fa65fd3ccffc33d9ff9/href">https://medium.com/media/1a5569d1ccbe1fa65fd3ccffc33d9ff9/href</a></iframe><p>İsterseniz bu noktada ilk olarak <strong><em>dependency injection</em></strong> tekniğini konuşalım. Ardından <strong><em>Spring Framework</em></strong>’de bunun ne şekilde uygulandığına değinelim. Daha sonra bir <strong><em>setter injection</em></strong> yöntemi olan <strong><em>Autowired </em></strong>anotasyonunun tavsiye edilmeme sebeplerini inceleyelim.</p><h3>Spring IOC Container</h3><p>Spring Framework, <strong><em>Program to Interface</em></strong> yaklaşımını benimser. Bu yaklaşımda sınıflar arasındaki bağımlılıklar <strong><em>interfaceler</em></strong> ve <strong><em>abstract sınıflar</em></strong> aracılığıyla sağlanır.</p><p>Kelime anlamı kontrolün tersine çevrilmesi olan <strong><em>IOC(Inversion of Control)</em></strong> modülerliği sağlayan bir prensip. Kontrolü geliştiriciden alıp başka bir aktöre mesela <em>framework’e </em>teslim ediyor. Kontrolü framework’e teslim ettiğimizde <strong><em>loosely coupling(gevşek bağlı)</em></strong> sağlıyoruz. Yani bir nesneyi yaratırken bağımlılıkları minimuma indiriyoruz.</p><p>Şimdi gelelim Spring Framework’e…</p><p>Biz geliştiriciler olarak java nesnelerini yaratmaktan sorumluyuz. İşte bu sorumluluk bizden alınıp <strong><em>Spring IOC Container</em></strong>’a geçiyor. <strong><em>Application context</em></strong> olarak da isimlendirilen Spring IOC Container, java nesnelerinin ihtiyaç duyulduğunda uygun parametre ve konfigürasyonlarla oluşturulmasını sağlıyor.</p><ul><li>Nesne bağımlılıkların sağlandığı concrete sınıfları bilmez.</li></ul><p>IOC’yi uygulamanın aşağıdaki resimde göreceğiniz gibi birçok yolu var. <strong><em>Dependency injection</em></strong>’da bunlardan birisi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*a06ozqf2PkImg4zeruqQ9w.png" /><figcaption>www.splessons.com</figcaption></figure><h4>Dependency Injection</h4><p>Yazılım mühendisliğinde bir nesne vasıtasıyla başka bir nesnenin bağımlılıklarının sağlandığı bir tekniktir.</p><blockquote><strong><em>Spring IOC Container</em></strong>’dan talep ettiğimiz onun factory metodu üzerinden üretilmiş sınıfın alınıp uygun bağımlılık olarak runtime’da inject edilmesine <strong><em>DI(dependency injection)</em></strong> deniyor.</blockquote><p>Dependency injection 3 farklı yöntemle yapılmaktadır.</p><ul><li>Constructor Injection (tavsiye edilen yöntem)</li><li>Setter Injection (Property Injection)</li><li>Method Injection</li></ul><p>Yazının konusu ve tavsiye edilen yöntem ise <strong><em>constructor injection</em></strong>. Aşağıda kullanım örneğini bulabilirsiniz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a7edddc4a4656039ca3c7216c392986/href">https://medium.com/media/1a7edddc4a4656039ca3c7216c392986/href</a></iframe><h4>Neden Constructor Injection ?</h4><ul><li><strong>Testability —</strong> NullPointer Exception’ı önleyerek testlerde hata alınması engeller. Testte, mock nesneleri constructora aktarmak kolaydır.</li></ul><p>Eğer Autowired kullanmış olsaydık testte aşağıdaki hatayı alıyor olacaktık. Bu yüzden Autowired kullanılması önerilmiyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-bMP-deUAQyg6MQC-Rhtg.jpeg" /></figure><ul><li><strong>Safety —</strong> Spring’i zorunlu bağımlılıkları sağlamaya zorlar. Oluşturulan nesnelerin constructiondan sonra valid durumda olduğundan emin oluruz.</li><li><strong>Readability —</strong> Constructor’a parametre olarak geçilen bağımlılıklar, zorunlu bağımlılıklardır. Property yada setter injection yöntemiyle sağlanan bağımlılıklar ise opsiyoneldir.</li></ul><p>Son olarak Spring ekibinin <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-dependencies"><strong><em>bu konudaki </em></strong></a>açıklamasını okumak isteyenler için bırakıyorum.</p><blockquote>Constructor-based or setter-based DI?</blockquote><blockquote>Since you can mix constructor-based and setter-based DI, it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies. Note that use of the <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-required-annotation">@Required</a> annotation on a setter method can be used to make the property be a required dependency; however, constructor injection with programmatic validation of arguments is preferable.</blockquote><blockquote>The Spring team generally advocates constructor injection, as it lets you implement application components as immutable objects and ensures that required dependencies are not null. Furthermore, constructor-injected components are always returned to the client (calling) code in a fully initialized state. As a side note, a large number of constructor arguments is a bad code smell, implying that the class likely has too many responsibilities and should be refactored to better address proper separation of concerns.</blockquote><blockquote>Setter injection should primarily only be used for optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency. One benefit of setter injection is that setter methods make objects of that class amenable to reconfiguration or re-injection later. Management through <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#jmx">JMX MBeans</a> is therefore a compelling use case for setter injection.</blockquote><blockquote>Use the DI style that makes the most sense for a particular class. Sometimes, when dealing with third-party classes for which you do not have the source, the choice is made for you. For example, if a third-party class does not expose any setter methods, then constructor injection may be the only available form of DI.</blockquote><p>Umarım faydalı olmuştur sizin için. Kaynak kodlara <a href="https://github.com/betul-sahin/spring-boot-dependency-injection"><strong><em>şu repodan</em></strong></a> ulaşabilirsiniz.</p><p>Keep coding ! 🚀</p><h3>Referans Kaynaklar</h3><ul><li><a href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-dependencies">Core Technologies</a></li><li><a href="https://kamer-dev.medium.com/spring-framework-1-ioc-ve-di-3e2da31bc0e5">Spring Framework | 1. IoC ve DI</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36b712523932" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Uygulamasını Dockerize Etmek ve Jib Maven Plugin’i Kullanımı]]></title>
            <link>https://medium.com/patika-dev/spring-boot-uygulamas%C4%B1n%C4%B1-dockerize-etmek-ve-jib-maven-plugini-kullan%C4%B1m%C4%B1-8b79fb29e740?source=rss-c720cfe5ef8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b79fb29e740</guid>
            <category><![CDATA[jib]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dockerhub]]></category>
            <category><![CDATA[maven-plugin]]></category>
            <dc:creator><![CDATA[Betül Şahin]]></dc:creator>
            <pubDate>Tue, 30 Nov 2021 08:07:26 GMT</pubDate>
            <atom:updated>2021-11-30T08:07:26.601Z</atom:updated>
            <content:encoded><![CDATA[<p>Bu yazıda Spring Boot uygulamasını <strong>dockerize</strong> etmeyi, dockerhub’a yüklemeyi ve <strong>dockerhub</strong>’a yükleme işlemlerini <strong>Maven Jib Plugin</strong>’i kullanarak<em> </em>otomatize etmeyi konuşacağız. Ayrıca temel docker komutlarını göreceğiz.</p><p><em>Bu yaz öğrenci olarak katılmış olduğum </em><a href="https://www.linkedin.com/company/gittigidiyor/"><em>GittiGidiyor</em></a><em> — </em><a href="https://www.linkedin.com/company/kodluyoruz/"><em>Kodluyoruz</em></a><em> &amp; </em><a href="https://www.linkedin.com/company/patikadev/"><em>Patika.dev</em></a><em> işbirliğiyle düzenlenen 113. GittiGidiyor Java Spring Bootcamp’inde öğrenmiş olduklarımı derledim. Katkılarından dolayı eğitmenimiz </em><a href="https://github.com/korayguney"><em>Koray Güney</em></a><em>’e ve arkadaşlarımız </em><a href="https://github.com/furkanisitan"><em>Furkan Işıtan</em></a><em> ile </em><a href="https://github.com/remziusta"><em>Remzi Usta</em></a><em>’ya teşekkür ediyorum.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L04mheM7ZXHbAHQpNz1R-A.jpeg" /></figure><p>Docker kelimesi <em>liman işçisi</em> anlamına geliyor.</p><p><strong>W</strong><a href="https://tr.wikipedia.org/wiki/Docker"><strong>ikipedia</strong></a><strong> </strong>’dan docker tanımına bakalım.</p><blockquote>Docker, “konteynerleştirme” olarak da bilinen işletim sistemi seviyesinde sanallaştırma sağlayan bir bilgisayar programıdır. İlk sürümü 2013&#39;te yayınlanmıştır.</blockquote><blockquote>Docker, “konteyner” (container) adı verilen yazılım paketlerini çalıştırmak için kullanılmaktadır. Konteynerler birbirinden izole edilmiş ve bağımsız halde çalışabilmektedir. Tüm konteynerler tek bir <a href="https://tr.wikipedia.org/wiki/%C3%87ekirdek_(bilgisayar_bilimi)">işletim sistemi çekirdeği</a> üzerinde çalışır ve bu sayede <a href="https://tr.wikipedia.org/wiki/Sanal_makine">sanal makinelerden</a> daha hafiftir. Konteynerler “imaj” (image) adı verilen salt-okunur dosya sistemlerinden oluşturulur.</blockquote><blockquote>Kısaca özetlemek gerekirse Docker sayesinde bilgisayarımıza PostgreSql veritabanı kurmadan uygulamamızda bu veritabanını kullanabiliyoruz. Docker ile tek bir komutla tüm sistemimizi ayağa kaldırabiliyoruz.</blockquote><h4>Image ve Container arasındaki fark nedir ?</h4><p>Bunu örnekleyerek açıklayacak olursam <strong><em>image’ı </em></strong>java sınıflarımız gibi düşünürsek <strong><em>container</em></strong>, bu sınıflardan <em>new</em> operatörüyle ürettiğimiz <em>instance</em>’lara karşılık geliyor.</p><h4>Dockerhub nedir ?</h4><p>Docker image’larımızı host ettiğimiz yer. Örneğin git ile versiyonladığımız projelerimizi yayınladığımız github gibi.</p><h3>Docker Kurulumu</h3><p>Docker’ı kullanabilmek için localinizde kurulu olmalı. Kurulum için <a href="https://www.docker.com/products/docker-desktop"><strong><em>şuradaki</em></strong></a> adresten işletim sisteminize uygun olanı indirebilirsiniz. Kurulum tamamlandığında aşağıdaki arayüzle karşılaşacaksınız. Sol alt köşe yeşilse başarılı bir şekilde çalışıyordur. <em>(Windows bilgisayarlarda yeşile dönmesi uzun sürebiliyor.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*TXJdQ47QA0C63AN4TSW6_Q.jpeg" /></figure><h3>Temel Docker Komutları</h3><ul><li><strong>docker —</strong> Docker komutlarını terminalden aşağıdaki komutla listeleyebilirsiniz.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker</strong></pre><ul><li><strong>docker help —</strong> Ayrıca aşağıdaki komutla da aynı listeye erişebilirsiniz.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker --help</strong></pre><p>Herhangi bir komut üzerinde detayları öğrenmek istediğimizde bu komutu şu şekilde kullanıyoruz. Örneğin <em>update </em>komutunun detaylarını öğrenelim.</p><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker update --help</strong></pre><ul><li><strong>docker image —</strong> Aşağıdaki komut tüm image’ları listeler.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker image ls</strong></pre><p>yada</p><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker images</strong></pre><ul><li><strong>docker rmi —</strong> Image silmek için Image Id’nin ilk 3–4 karakterini yazmak yeterli oluyor. Örneğin hello-world’ü silmek için.</li></ul><pre>| REPOSITORY  | TAG    | IMAGE ID     | CREATED     | SIZE   |<br>| ----------- | ------ | ------------ | ----------- | ------ |<br>| hello-world | latest | feb5d9fea6a5 | 4 weeks ago | 13.3kB |</pre><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker rmi feb5</strong></pre><ul><li><strong>docker run —</strong> <strong><em>Dockerhub</em></strong>’da yer alan bir image’ı çekmek ve çalıştırmak için aşağıdaki komutu kullanıyoruz. Örneğin <a href="https://hub.docker.com/_/hello-world">şu image’ı</a> çalıştıralım.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker run hello-world</strong></pre><ul><li><strong>docker pull —</strong> Çalıştırmayıp yalnızca localimize çekmek isteseydik şu komutu kullanacaktık.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker pull hello-world</strong></pre><ul><li><strong>docker container —</strong> hello-world image’ı çalıştı görevini tamamladı ve durdu. Aşağıdaki komut çalışmış ve ölmüş olan atıl durumdaki containerları listeler.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker container ls -a</strong></pre><p>Çalışmakta olan tüm containerları ise şu komutla listeliyoruz.</p><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker container ls</strong></pre><ul><li><strong>docker ps —</strong> Çalışan docker containerlarını listelemek için diğer bir komut şu. Yine bu komutunda sonuna ”<em>-a”</em> ekleyerek atıl durumda olanları görebiliriz.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker ps</strong></pre><ul><li><strong>docker stop —</strong> Çalışan containerı durdurmak için aşağıdaki komutu kullanıyoruz.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker stop &lt;CONTAINER_ID&gt;</strong></pre><ul><li><strong>docker rm —</strong> Container silmek için ise şu komutu kullanıyoruz.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker rm &lt;CONTAINER_ID&gt;</strong></pre><ul><li><strong>prune —</strong> Durmuş olan tüm containerları tek bir komutla silmek için ise aşağıdaki komutu kullanıyoruz.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker container prune</strong></pre><p><strong><em>Diğer docker komutları için </em></strong><a href="https://docs.docker.com/engine/reference/commandline/docker/"><strong><em>şu referanstan</em></strong></a><strong><em> devam edebilirsiniz.</em></strong></p><h3>Spring Boot / PostgreSql Projesini Dockerize Etmek</h3><blockquote><em>Spring Boot</em> ve <em>PostgreSql</em> kullanarak hazırladığım basit bir <em>Restfull</em> uygulaması üzerinden ilerleyeceğiz. Projemizde bir tane api bulunuyor ve bununla ürün ekleyebiliyor/listeleyebiliyoruz. Örnek projeye <a href="https://github.com/betul-sahin/springboot-docker-maven-jib-plugin"><strong><em>bu adresten</em></strong></a> ulaşabilirsiniz.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*NUa6-E402R5HofwCy-Vmsg.jpeg" /></figure><p>Docker’ın, <strong><em>Dockerfile</em></strong> adında bir konfigürasyon dosyası var. Yeni bir docker image’i create etmemizi sağlıyor. Mevcut uygulamamızı bu dosya içerisinde yazacağımız ayarlara göre <strong><em>dockerize </em></strong>ediyoruz. Yani konteynırlaştırıyoruz.</p><h4>Dockerfile Oluşturmak</h4><p>Projenin ana klasörüne aşağıdaki <em>Dockerfile</em> dosyasını oluşturuyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d441bd5e811888275f5f5f7355b744ba/href">https://medium.com/media/d441bd5e811888275f5f5f7355b744ba/href</a></iframe><ul><li><strong><em>FROM</em></strong> : Spring projesinin çalışabilmesi için JDK’ya ihtiyacımız var. Bunun için Java platformunun open source implementasyonu olan OpenJDK’yı kullanıyoruz.</li><li><strong><em>EXPOSE</em></strong> : Hangi port üzerinde koşacağını söylüyoruz.</li><li><strong><em>ADD</em></strong> : jar dosyamizi isimlendiriyoruz. <em>target </em>altındaki jar dosyamiza yeni isim veriyoruz.</li><li><strong><em>ENTRYPOINT</em></strong> : executable olarak bir iş yapmasını sağlıyoruz. Terminal üzerinden bir jar dosyasını çalıştırma mantığıyla hareket ediyoruz.</li></ul><p>Bu dosyayı oluşturduktan sonra uygulamamızı dockerize etmek için aşağıdaki komutu çalıştırıyoruz.</p><pre><strong>docker build -t spring-docker-demo .</strong></pre><p>Burada <em>“-t”</em> den sonra tag ismini yazıyoruz. (İstediğimiz isimlendirmeyi yapabiliriz.)</p><p>“.” sondaki nokta ise build ettiği image’ı bulunduğu klasöre koyacağını gösteriyor.</p><p>Aşağıdaki gibi bir çıktı alıyor olacaksınız. Böylece Spring projemizin Docker image’ini oluşturduk!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*bPxteHbtu8kR6PR7Wu7A0Q.jpeg" /></figure><p>Oluşturduğumuz image’i localde çalıştırmak için aşağıdaki komutu kullanıyoruz.</p><pre><strong>docker run -p 8080:8080 spring-docker-demo</strong></pre><p>Burada <em>“8080:</em><strong><em>8080</em></strong><em>”</em> ikinci bölüm uygulamayı localde ayağa kaldıracağımız port oluyor. Örneğin <em>“8080:</em><strong><em>9090</em></strong><em>”</em> yazmış olsaydık uygulamamız <em>“localhost:9090”</em> da çalışırdı.</p><p><em>Dikkat ettiyseniz şimdiye kadar PostgreSql konfigürasyonlarını yapmadık. Bu yüzden çalıştırdığınızda aşağıdaki hatayı almış olabilirsiniz. İleride bunu düzelteceğiz.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpqduqCI22hgASS4wB5h-A.jpeg" /></figure><h4>Dockerhub’a Yüklemek</h4><p>Oluşturduğumuz docker image’ını <strong><em>dockerhub</em></strong>’a yükleyerek global erişim sağlıyoruz. Herhangi birisi erişim sağlayarak kendi localinde uygulamamızı çalıştırabiliyor.</p><p>İlk olarak <a href="https://hub.docker.com/"><em>buradan</em></a> hesabınızı oluşturmalısınız. Ardından terminalden aşağıdaki komutu çalıştırarak login olmalısınız.</p><pre><strong>docker login</strong></pre><p>Image ismini <em>dockerhub </em>kullanıcı adımıza göre taglıyoruz.</p><pre><strong>docker tag spring-docker-demo betulsahinn/spring-docker-demo</strong></pre><p>Ardından aşağıdaki <strong><em>push </em></strong>komutuyla image’ı dockerhub’a yüklüyoruz.</p><pre><strong>docker push betulsahinn/spring-docker-demo</strong></pre><p>Yüklediğimiz image’ı ise pull komutuyla localimize çekebiliyoruz. Yada run komutuyla aynı anda hem localimize çekip hem de çalıştırabiliyoruz.</p><pre><strong>docker pull betulsahinn/spring-docker-demo</strong></pre><pre><strong>docker run betulsahinn/spring-docker-demo</strong></pre><h4>docker-compose.yml Dosyası Oluşturmak</h4><p>Bu dosya birden fazla containerı aynı anda çalıştırabilmemize olanak tanıyor. Detaylı bilgi için <a href="https://medium.com/devopsturkiye/docker-compose-4d2a8db99b47"><em>şuradaki</em></a> yazıya gidebilirsiniz.</p><p>PostgreSql veritabanını docker üzerinden çalıştırmak için projenin ana klasörüne <em>docker-compose.yml</em> isimli aşağıdaki dosyayı oluşturuyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd36cbdadbd1349d37e70b729cad3049/href">https://medium.com/media/cd36cbdadbd1349d37e70b729cad3049/href</a></iframe><p>Ardından aşağıdaki komutla projeyi ayağa kaldırıyoruz.</p><pre><strong>docker-compose -f docker-compose.yml up -d</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*ncWquB6bC8jKCh8gJl8ZDQ.jpeg" /></figure><p><strong><em>Ayrıca veritabanı oluşturmanıza lüzum yok kendisi otomatik oluşturuyor. Çok iyi değil mi ?</em></strong></p><p>Tüm işlemleri başarıyla tamamladıysanız <a href="http://localhost:8080/swagger-ui.html">http://localhost:8080/swagger-ui.html</a> adresine giderek aşağıdaki ekrana ulaşmış olmalısınız. Gördüğünüz gibi herhangi bir kurulum ihtiyacı duymadan tek bir komutla tüm sistemi ayağa kaldırdık.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*a11ef4b0rcmH3ZF76QsP2g.jpeg" /></figure><h3>Jib Maven Plugini Kullanımı</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*0THrb0akmUtVFU17VWMcsw.jpeg" /></figure><p>Şimdi tüm bu işlemleri maven plugini olan <a href="https://github.com/GoogleContainerTools/jib/tree/master/jib-maven-plugin"><strong><em>jib</em></strong></a> kullanarak otomatize edeceğiz. Böylece uygulamayı dockerize etme ve Dockerhub’a yükleme işlemlerini <a href="https://github.com/GoogleContainerTools/jib/tree/master/jib-maven-plugin"><em>jib maven plugin</em></a>’i bizim yerimize gerçekleştirecek.</p><p>İlk olarak aşağıdaki <em>jib maven plugin</em> deklarasyonunu, pom.xml dosyamızda <em>&lt;plugins&gt;&lt;/plugins&gt;</em> bölümüne koyuyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b6eca0397ba28fe7ea478f5d13d1519/href">https://medium.com/media/1b6eca0397ba28fe7ea478f5d13d1519/href</a></iframe><p>Yukarıdaki deklarasyon ile containerımızı oluşturuyoruz.</p><p><em>&lt;configuration&gt;&lt;/configuration&gt;</em> bölümünde docker image konfigürasyonunu temel seviyede yaptık. Ayrıntı bilgi için <a href="https://github.com/GoogleContainerTools/jib/tree/master/jib-maven-plugin"><em>jib resmi sayfasına</em></a> bakabilirsiniz.</p><p>Ardından <em>jib plugin</em>’i ile deklare ettiğimiz <em>Docker image</em>’nı build etmek için aşağıdaki komutu kullanıyoruz.</p><pre>mvn clean install <strong>jib:dockerBuild</strong> -Djib.to.image=<strong>spring-docker-demo:v1</strong></pre><p><em>Bu komutu çalıştırdıktan sonra aşağıdaki warningleri alabilirsiniz. Bu durumda aynı komutu tekrar çalıştırırsanız warningler kalkacaktır.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BsXh9II3uiC4Xi1HyMK3oA.jpeg" /></figure><p>Jib ile oluşturduğumuz docker image’ını yine aynı şekilde terminale aşağıdaki komutları yazarak localhost:8080 ‘de çalıştırabilirsiniz.</p><pre>docker run -p 8080:<strong>8080</strong> spring-docker-demo:v1</pre><p>İkinci olarak ise image’ı, dockerhub’a jib komutlarıyla pushlayalım. Burada taglama yaparken <strong><em>dockerhub kullanıcı adı</em></strong>mızı yazıyoruz ve versiyon veriyoruz.</p><pre>mvn clean install <strong>jib:build</strong> -Djib.to.image=<strong>betulsahinn/spring-docker-demo:v1</strong></pre><ul><li>Warning alırsanız aynı komutu tekrar çalıştırın.</li></ul><p>Şimdi bu komutla yaptığımız dockerhub push işlemini jib pluginlerini kullanarak otomatize edelim.</p><p>Bunun için ilk olarak pom.xml dosyasında <strong><em>properties </em></strong>bölümüne aşağıdaki eklemeleri yapalım.</p><pre>&lt;properties&gt;<br>   &lt;java.version&gt;1.8&lt;/java.version&gt;<br>   <strong>&lt;app.image.name&gt;spring-docker-demo&lt;/app.image.name&gt;<br>   &lt;app.image.tag/&gt;</strong><br>&lt;/properties&gt;</pre><p>Ardından pom.xml dosyasına profil tanımlıyoruz. Aşağıdaki deklarasyonu &lt;/plugins&gt;&lt;/build&gt; etiketini kapattıktan sonra ekliyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/100d642fae10870fb5bfb69969640f71/href">https://medium.com/media/100d642fae10870fb5bfb69969640f71/href</a></iframe><p>İlk profil dockerhub’a pushlarken ikinci profil locale pushlamaktadır. Yani localde image oluşması için.</p><p>Maven bölümünden profilleri aşağıdaki ikinci resimdeki gibi işaretleyip komutu çalıştırınız. Uygulamaya <strong><em>tag </em></strong>ismi vermedik properties bölümünde tanımladığımız için. Yalnızca versiyon vermemiz yeterli.</p><pre>mvn clean install <strong>-P jib-push-to-dockerhub</strong> -Dapp.image.tag=v2</pre><p>Ardından dockerhub hesabınızı kontrol ederseniz oraya yüklenmiş olduğunu göreceksiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5F_PGo1zLgjI9yAT365Dvg.jpeg" /></figure><p><em>Komut yazmakla uğraşmak istemezseniz maven bölümünden profilleri seçip </em><strong><em>mvn clean install</em></strong><em> komutunu çalıştırarak aynı işlemleri yapabilirsiniz.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*jmW7LC_Y7irIwIn69UjB6Q.jpeg" /></figure><p>Dockerhub’a gönderdiğiniz projeyi localde çalıştırmak için image isminin başına <strong><em>dockerhub kullanıcı adı</em></strong>nızı eklemeyi unutmayın.</p><pre>docker run -p 8080:<strong>8080</strong> <strong>betulsahinn/</strong>spring-docker-demo:v1</pre><p>Umarım faydalı olmuştur sizin için. Projenin tamamına <a href="https://github.com/betul-sahin/springboot-docker-maven-jib-plugin"><strong><em>şu repodan</em></strong></a> ulaşabilirsiniz.</p><p>Happy coding ! 🚀</p><h4><strong>Referans Kaynaklar</strong></h4><ul><li><a href="https://tr.wikipedia.org/wiki/Docker">Docker - Vikipedi</a></li><li><a href="https://docs.docker.com/engine/reference/commandline/docker/">docker</a></li><li><a href="https://medium.com/devopsturkiye/docker-compose-4d2a8db99b47">Docker Compose</a></li><li><a href="https://github.com/GoogleContainerTools/jib/tree/master/jib-maven-plugin">jib/jib-maven-plugin at master · GoogleContainerTools/jib</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b79fb29e740" width="1" height="1" alt=""><hr><p><a href="https://medium.com/patika-dev/spring-boot-uygulamas%C4%B1n%C4%B1-dockerize-etmek-ve-jib-maven-plugini-kullan%C4%B1m%C4%B1-8b79fb29e740">Spring Boot Uygulamasını Dockerize Etmek ve Jib Maven Plugin’i Kullanımı</a> was originally published in <a href="https://medium.com/patika-dev">Patika.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerizing a Spring Boot Application and Using the Jib Maven Plugin]]></title>
            <link>https://betulsahinn.medium.com/dockerizing-a-spring-boot-application-and-using-the-jib-maven-plugin-95c329866f34?source=rss-c720cfe5ef8------2</link>
            <guid isPermaLink="false">https://medium.com/p/95c329866f34</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[jib-maven-plugin]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Betül Şahin]]></dc:creator>
            <pubDate>Tue, 23 Nov 2021 12:13:51 GMT</pubDate>
            <atom:updated>2021-11-24T05:21:09.803Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, we’ll talk about <strong><em>dockerizing the Spring Boot applications using dockerfile</em></strong> and docker tool. Then we’ll also publish the Docker image to dockerhub.</p><p>And then we’ll be doing all of these steps with the help of <strong><em>Maven Jib Plugin.</em></strong></p><p><em>Here, I shared what I learned in the </em><a href="https://www.patika.dev/programlar/gittigidiyor-java-spring-bootcamp"><em>Java &amp; Spring Framework Bootcamp</em></a><em> organized in collaboration with </em><a href="https://www.gittigidiyor.com/"><em>GittiGidiyor</em></a><em> — </em><a href="https://www.kodluyoruz.org/"><em>Kodluyoruz</em></a><em> &amp; </em><a href="https://www.patika.dev/"><em>Patika.dev</em></a><em>, which I attended this summer as a student.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L04mheM7ZXHbAHQpNz1R-A.jpeg" /></figure><h3>What is Docker?</h3><p><strong><em>Wikipedia</em></strong> defines <a href="https://www.docker.com/">Docker</a> as</p><blockquote>Docker can package an application and its dependencies in a virtual container that can run on any Linux, Windows, or macOS computer. This enables the application to run in a variety of locations, such as on-premises, in a public cloud, and/or in a private cloud. When running on Linux, Docker uses the resource isolation features of the Linux kernel (such as cgroups and kernel namespaces) and a union-capable file system (such as OverlayFS) to allow containers to run within a single Linux instance, avoiding the overhead of starting and maintaining virtual machines. Docker on macOS uses a Linux virtual machine to run the containers.</blockquote><blockquote>Because Docker containers are lightweight, a single server or virtual machine can run several containers simultaneously. A 2018 analysis found that a typical Docker use case involves running eight containers per host, and that a quarter of analyzed organizations run 18 or more per host.</blockquote><blockquote>To summarize briefly, we can use PostgreSql database via Docker in our application without installing a PostgreSql database on our computer . With Docker, we can up our entire system with a single command.</blockquote><h4>What is the difference between Image and Container ?</h4><p>Let’s clarify this with an example. If we think of Docker images as a java classes, the container corresponds to the instances we produce with the new operator from these classes.</p><h4>What is Dockerhub ?</h4><p>Where we host our Docker images. For example, github where we host our projects that we versioned with git.</p><h3>Docker Installation</h3><p>For installation, you can download the appropriate one for your operating system from <a href="https://www.docker.com/products/docker-desktop"><strong><em>that address</em></strong></a><strong><em>.</em></strong> Once the installation is complete, you will see the following screen. If the lower left corner is green, it is working successfully. <em>(it can take a long time to turn green on Windows computers.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*TXJdQ47QA0C63AN4TSW6_Q.jpeg" /></figure><h3>Common Docker Commands</h3><p>Here are a few of the basic commands from the Docker CLI reference we often use.</p><ul><li><strong>docker —</strong> lists Docker commands from terminal.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker</strong></pre><ul><li><strong>docker help —</strong> You can also access the same list with the following command.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker --help</strong></pre><p>If you want to learn the details on any command, you can use this command as follows. For example, let’s learn the details of the update command.</p><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker update --help</strong></pre><ul><li><strong>docker image —</strong> lists all images.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker image ls</strong></pre><p>or</p><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker images</strong></pre><ul><li><strong>docker rmi —</strong> removes an image using its short ID( first 3–4 characters).</li></ul><pre>| REPOSITORY  | TAG    | IMAGE ID     | CREATED     | SIZE   |<br>| ----------- | ------ | ------------ | ----------- | ------ |<br>| hello-world | latest | feb5d9fea6a5 | 4 weeks ago | 13.3kB |</pre><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker rmi feb5</strong></pre><ul><li><strong>docker run —</strong> runs an image from Dockerhub.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker run hello-world</strong></pre><ul><li><strong>docker pull — p</strong>ulls an image from Dockerhub.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker pull hello-world</strong></pre><ul><li><strong>docker container — </strong>shows all containers with inactive containers that have run and died.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker container ls -a</strong></pre><p>This command lists all <strong><em>running containers</em></strong>.</p><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker container ls</strong></pre><ul><li><strong>docker ps —</strong> Another command to list running docker containers. we can see the inactive containers by adding “-a” to the end of this command.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker ps</strong></pre><ul><li><strong>docker stop —</strong> stops the running container.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker stop &lt;CONTAINER_ID&gt;</strong></pre><ul><li><strong>docker rm —</strong> removes the container.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker rm &lt;CONTAINER_ID&gt;</strong></pre><ul><li><strong>prune —</strong> removes all stopped containers with a single command.</li></ul><pre>C:\springboot-docker-maven-jib-plugin&gt; <strong>docker container prune</strong></pre><p><strong><em>For other docker commands, you can continue from </em></strong><a href="https://docs.docker.com/engine/reference/commandline/docker/"><strong><em>this reference</em></strong></a><strong><em>.</em></strong></p><h3>Dockerize a Spring Boot Application</h3><blockquote>I built a simple Restfull application using Spring Boot to get some data from the PostgreSql database. There is an API in the project that we can add/list products with it. You can access the sample project at <a href="https://github.com/betul-sahin/springboot-docker-maven-jib-plugin">this address</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*NUa6-E402R5HofwCy-Vmsg.jpeg" /></figure><p>Docker has a configuration file called <strong><em>Dockerfile</em></strong>. This file allows you to create a new docker image. So we <strong>containerize </strong>with it.</p><h4>Creating a Dockerfile</h4><p>We create the following <em>Dockerfile </em>in the main folder of the project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d441bd5e811888275f5f5f7355b744ba/href">https://medium.com/media/d441bd5e811888275f5f5f7355b744ba/href</a></iframe><ul><li><strong><em>FROM —</em></strong> We need the JDK for the Spring application to run. For this, we use OpenJDK, which is the open source implementation of the Java platform.</li><li><strong><em>EXPOSE — </em></strong>tells which port it will run on.</li><li><strong><em>ADD —</em></strong> naming the jar file. Renames the jar file under <em>target </em>directory.</li><li><strong><em>ENTRYPOINT —</em></strong> is to set the image’s main command, allowing that image to be run as though it was that command. So it makes it do something as executable.</li></ul><p>After creating this file, we run the following command to dockerize our application.</p><pre><strong>docker build -t spring-docker-demo .</strong></pre><p>Here we write the tag name after “-t”. (We can name whatever we want.)</p><p>“.” The dot at the end shows that it will put the image it has built in the folder it is in.</p><p>You will get an output like below. So we created the docker image of our Spring application!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*bPxteHbtu8kR6PR7Wu7A0Q.jpeg" /></figure><p>We use the following command to run the image we created locally.</p><pre><strong>docker run -p 8080:8080 spring-docker-demo</strong></pre><p>Here, the second part of <em>“8080:</em><strong><em>8080</em></strong><em>”</em> is the port where we will run the application locally. For example, <em>“8080:</em><strong><em>9090</em></strong><em>”</em> shows us to our application will run at “localhost:9090”.</p><p><em>Did you notice that we haven’t done the PostgreSql configurations of our application until now. So when you run the container you might receive the following errors. We’ll fix it later.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpqduqCI22hgASS4wB5h-A.jpeg" /></figure><h4>Uploading to Dockerhub</h4><p>We provide public access by uploading the docker image we created to dockerhub. Anyone can get access to free public repositories for storing and sharing images.</p><p>First you can create a <a href="https://hub.docker.com/signup"><em>free account here</em></a>. Then you need to login by running the following command from the terminal.</p><pre><strong>docker login</strong></pre><p>We tag the image name according to our dockerhub username.</p><pre><strong>docker tag spring-docker-demo betulsahinn/spring-docker-demo</strong></pre><p>Then we upload the image to dockerhub with the following <strong><em>push </em></strong>command.</p><pre><strong>docker push betulsahinn/spring-docker-demo</strong></pre><p>We can pull the uploaded image to our local with the <strong><em>pull </em></strong>command. Or with the <strong><em>run </em></strong>command, we can pull it to our local and run it at the same time.</p><pre><strong>docker pull betulsahinn/spring-docker-demo</strong></pre><pre><strong>docker run betulsahinn/spring-docker-demo</strong></pre><h4>Creating a docker-compose.yml</h4><p>This file allows us to run multiple containers simultaneously. For detailed information, you can go to the <a href="https://docs.docker.com/compose/#:~:text=Compose%20is%20a%20tool%20for,the%20services%20from%20your%20configuration."><em>here</em></a>.</p><p>We create the following file named docker-compose.yml in the main folder of the project. It contains keywords <strong><em>backend </em></strong>and <strong><em>PostgreSQL</em></strong>, which defines services for web and database portions of the application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd36cbdadbd1349d37e70b729cad3049/href">https://medium.com/media/cd36cbdadbd1349d37e70b729cad3049/href</a></iframe><p>Then we start the project with the following command.</p><pre><strong>docker-compose -f docker-compose.yml up -d</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*ncWquB6bC8jKCh8gJl8ZDQ.jpeg" /></figure><p><strong><em>You don’t need to create a database, it creates it automatically. Isn’t it very good?</em></strong></p><p>After following the steps listed in the tutorial, you will reach the swagger ui at <em>localhost:8080/swagger-ui.html</em>. As you can see, we run the entire system with a single command without the need for any installation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*a11ef4b0rcmH3ZF76QsP2g.jpeg" /></figure><h3>Using Jib Maven Plugin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*0THrb0akmUtVFU17VWMcsw.jpeg" /></figure><p>Now we will simplifies containerization of Spring application using Jib, which is a maven plugin. We’ll build its docker image using jib. And then we’ll also upload the image to Dockerhub using Jib.</p><p>First, put the following <strong><em>jib maven plugin</em></strong> declaration in the <em>&lt;plugins&gt;&lt;/plugins&gt;</em> section of your pom.xml file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b6eca0397ba28fe7ea478f5d13d1519/href">https://medium.com/media/1b6eca0397ba28fe7ea478f5d13d1519/href</a></iframe><p>We create our container with the above declaration.</p><p>In the <em>&lt;configuration&gt;&lt;/configuration&gt;</em> section, we have configured the docker image at the basic level. For detailed information, you can check the <a href="https://github.com/GoogleContainerTools/jib/tree/master/jib-maven-plugin">jib official page</a>.</p><p>Then we use the following command to build the <em>docker image</em> that we declared with the <em>jib plugin</em>.</p><pre>mvn clean install <strong>jib:dockerBuild</strong> -Djib.to.image=<strong>spring-docker-demo:v1</strong></pre><p><em>After running this command, you may get the following warnings. Run the same command again.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BsXh9II3uiC4Xi1HyMK3oA.jpeg" /></figure><p>You can run the docker image we created with Jib at <em>localhost:8080</em> by typing the following commands in the terminal.</p><pre>docker run -p 8080:<strong>8080</strong> spring-docker-demo:v1</pre><p>Secondly, let’s push the image to dockerhub with jib commands. While tagging here, write <strong><em>your dockerhub username</em></strong> and the version.</p><pre>mvn clean install <strong>jib:build</strong> -Djib.to.image=<strong>betulsahinn/spring-docker-demo:v1</strong></pre><ul><li><strong>If you get a warning, run the same command again.</strong></li></ul><p>Now, let’s simplfy the dockerhub push with this command using jib plugins.</p><p>First of all, let’s make the following additions to the <strong><em>properties </em></strong>section of the pom.xml file.</p><pre>&lt;properties&gt;<br>   &lt;java.version&gt;1.8&lt;/java.version&gt;<br>   <strong>&lt;app.image.name&gt;spring-docker-demo&lt;/app.image.name&gt;<br>   &lt;app.image.tag/&gt;</strong><br>&lt;/properties&gt;</pre><p>Then we define the profile in the pom.xml file. We add the following declaration after closing the <em>&lt;/plugins&gt;&lt;/build&gt;</em> tag.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/100d642fae10870fb5bfb69969640f71/href">https://medium.com/media/100d642fae10870fb5bfb69969640f71/href</a></iframe><p>The first profile is for pushing to dockerhub and the second profile is for pushing to locale.</p><p>From the Maven section, mark the profiles as in the second picture below and run the command. We did not give a tag name to the application because we defined it in the properties section. We just need to give the version.</p><pre>mvn clean install <strong>-P jib-push-to-dockerhub</strong> -Dapp.image.tag=v2</pre><p>Then if you check <strong><em>your dockerhub account </em></strong>you will see that it is uploaded there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5F_PGo1zLgjI9yAT365Dvg.jpeg" /></figure><p><em>To run without using jib commands, select profiles from the maven section and run </em><strong><em>mvn clean install </em></strong><em>command.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*jmW7LC_Y7irIwIn69UjB6Q.jpeg" /></figure><p>Do not forget to add <strong>your dockerhub username </strong>to the beginning of the image name to run the project you sent to Dockerhub locally.</p><pre>docker run -p 8080:<strong>8080</strong> <strong>betulsahinn/</strong>spring-docker-demo:v1</pre><p>I hope it was useful for you. You can access the whole project from <a href="https://github.com/betul-sahin/springboot-docker-maven-jib-plugin">this repo.</a></p><p>Keep coding ! 🚀</p><h4>Reference Resources</h4><ul><li><a href="https://en.wikipedia.org/wiki/Docker_(software)">Docker (software) - Wikipedia</a></li><li><a href="https://docs.docker.com/engine/reference/commandline/docker/">docker</a></li><li><a href="https://github.com/GoogleContainerTools/jib/tree/master/jib-maven-plugin">jib/jib-maven-plugin at master · GoogleContainerTools/jib</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95c329866f34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anroid Searchview ile Uygulamaya Arama İşlevselliği Eklemek]]></title>
            <link>https://betulsahinn.medium.com/anroid-searchview-ile-uygulamaya-arama-i%CC%87%C5%9Flevselli%C4%9Fi-eklemek-164c53417655?source=rss-c720cfe5ef8------2</link>
            <guid isPermaLink="false">https://medium.com/p/164c53417655</guid>
            <category><![CDATA[searchview]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Betül Şahin]]></dc:creator>
            <pubDate>Tue, 16 Nov 2021 19:02:25 GMT</pubDate>
            <atom:updated>2021-11-16T19:54:58.007Z</atom:updated>
            <content:encoded><![CDATA[<p>Bu yazıda uygulamaya <strong><em>Searchview</em></strong> kullanarak arama işlevselliği ekleyeceğiz. <em>Android geliştirici dökümanı üzerinden ilerleyeceğiz.</em> Bunun için üç aşamadan oluşan aşağıdaki adımları takip edeceğiz.</p><ol><li><strong>Arama Arayüzünü Ayarlamak</strong><br>Uygulamaya nasıl arama arayüzü ekleneceğini ve arama sorgularını işlemek için activity’nin nasıl yapılandırılacağını öğreneceğiz.</li><li><strong>Veri Depolamak ve Aramak</strong><br><em>SQLite sanal veritabanı </em>tablosunda verilerin nasıl saklandığını ve sorgulandığını öğreneceğiz.</li><li><strong>Geriye Doğru Uyumluluk</strong><br>Arama özelliklerinin, eski cihazlarla geriye dönük olarak uyumluluğunu nasıl sağlayacağımızı öğreneceğiz.</li></ol><p><em>Konuyu öğrenirken basit bir İngilizce sözlük uygulaması yazacağız. Çalışma tamamlandığında aşağıdaki gibi görünecek.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ITYHcQTXQ5ne_9dG5n0xzg.jpeg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMt8IlpLfDKM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMt8IlpLfDKM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMt8IlpLfDKM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/89e1cc19f42bfa62b624fd47f10eb45f/href">https://medium.com/media/89e1cc19f42bfa62b624fd47f10eb45f/href</a></iframe><h3><strong>1. Arama Arayüzünü Ayarlamak</strong></h3><p>Uygulama çubuğuna, SearchView widget’ı konularak uygulamaya arama özelliği eklenmektedir. Bu yöntem Android 3.0&#39;dan bu yana tercih edilmektedir.</p><p><strong><em>App Bar’a SearchView Ekleme</em></strong></p><p>Uygulama çubuğuna bir <em>SearchView widget’ı </em>eklemek için projede <strong>res/menu/options_menu.xml</strong> adlı bir dosya oluşturuyoruz. Bunu yapmak için sol yan bölümden <strong><em>res</em></strong> klasörüne sağ tıklayıp <strong><em>New-&gt;Android Resource File</em></strong>’ı seçiyoruz. Açılan pencerede dosya adı alanına <strong><em>options_menu.xml </em></strong>yazıp kaynak tipini <strong><em>menu </em></strong>olarak belirliyoruz. Dosyaya aşağıdaki kodu ekliyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b74c31727cbdc965123002d77d7d49b9/href">https://medium.com/media/b74c31727cbdc965123002d77d7d49b9/href</a></iframe><p><em>options_menu.xml</em> dosyasıyla arama öğesi olarak kullanılacak simge ve başlık yazısı belirledik. <strong><em>showAsAction</em></strong> özelliğini <strong><em>collapseActionView|ifRoom</em></strong><em> </em>olarak belirledik.</p><p><strong>showAsAction’a geçtiğimiz öznitelikler ne anlama geliyor ?</strong></p><ul><li><strong><em>collapseActionView:</em></strong> SearchView tüm uygulama çubuğunu kaplar ve kullanılmadığında normal boyutuna geri küçülür.</li><li><strong><em>ifRoom:</em></strong> Uygulama çubuğunda yer varsa öğenin simgesi gösterilir yer yoksa öğe taşma menüsünde görüntülenir.</li></ul><p>SearchView’i uygulama çubuğunda göstermek için activity’nin <strong><em>onCreateOptionsMenu()</em></strong> metodunda menü dosyasını(res/menu/options_menu.xml) inflate ediyoruz.</p><pre>@Override<br>public boolean onCreateOptionsMenu(Menu menu) {<br>    MenuInflater inflater = getMenuInflater();<br>    inflater.inflate(R.menu.options_menu, menu);<br><br>    return true;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*1SeFbnX_vj9VW-sVICX_HQ.png" /></figure><p>Uygulamayı çalıştırdığınızda yandaki gibi görünecektir. Arama simgesine tıkladığınızda herhangi bir işlem yapmayacaktır. Çünkü henüz nasıl davranacağını tanımlamadık.</p><p><strong><em>showAsAction</em></strong><em>’ın özniteliklerini değiştirerek diğer öznitelikler ile nasıl görüneceğini inleceyebilirsiniz.</em></p><p><strong><em>Arama Yapılabilecek Şekilde Yapılandırma (Searchable Configuration)</em></strong></p><p>Burada yapılandırmadan kastedilen SearchView’in nasıl davranacağını tanımlamak.</p><p>İlk olarak projede <strong>res/xml/searchable.xml</strong> dosyasını oluşturup aşağıdaki kodları ekliyoruz. <em>searchable.xml</em> dosyası en azından, Android manifest’inizdeki <em>&lt;application&gt;</em> veya <em>&lt;activity&gt;</em> öğesinin <em>android: label</em> özelliğiyle aynı değere sahip bir <strong><em>android: label</em></strong> özelliği içermelidir. Bununla birlikte, kullanıcıya arama kutusuna ne gireceği hakkında bir fikir vermek için <strong><em>android: hint</em></strong> özelliği eklenmesi öneriliyor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64301bfce1c19f9a2b84dbfd2834dd0a/href">https://medium.com/media/64301bfce1c19f9a2b84dbfd2834dd0a/href</a></iframe><p>Şimdi <strong><em>AndroidManifest</em></strong>’te bu dosyaya işaret eden bir <em>&lt;meta-data&gt;</em> öğesi bildiriyoruz.</p><pre>&lt;activity ... &gt;<br>    ...<br>    <strong>&lt;meta-data android:name=&quot;android.app.searchable&quot;<br>            android:resource=&quot;@xml/searchable&quot; /&gt;</strong><br><br>&lt;/activity&gt;</pre><p>Son olarak daha önce oluşturduğumuz <strong><em>onCreateOptionsMenu()</em></strong> metodunda, setSearchableInfo () metodunu çağırarak aranabilir yapılandırmayı(searchable.xml) SearchView ile ilişkilendiriyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88822d012dd657b551166a13143f15c6/href">https://medium.com/media/88822d012dd657b551166a13143f15c6/href</a></iframe><p>Kullanıcı bir sorgu gönderdiğinde SearchView, <em>ACTION_SEARCH</em> intenti ile bir activity başlatır. Şimdi bu intenti filtreleyebilecek ve arama sorgusunu işleyebilecek bir activity‘e ihtiyacımız var.</p><p><strong><em>Aranabilir Activity Oluşturma</em></strong></p><p><strong><em>AndroidManifest</em></strong>’te <em>A</em>ctivity’i, <em>ACTION_SEARCH</em> intentini filtrelemek üzere bildiriyoruz.</p><pre>&lt;activity android:name=&quot;.MainActivity&quot; ... &gt;<br>    ...<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;android.intent.action.SEARCH&quot; /&gt;<br>    &lt;/intent-filter&gt;<br>    ...<br>&lt;/activity&gt;</pre><p><em>MainActivity’nin </em><strong><em>onCreate()</em></strong> metodunda <strong><em>ACTION_SEARCH</em></strong> intentini kullanarak kullanıcının girmiş olduğu arama sorgusunu alıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7dbacf7db82ac7f8a1a17ef22c2768b/href">https://medium.com/media/f7dbacf7db82ac7f8a1a17ef22c2768b/href</a></iframe><p>Buraya kadar uygulamamıza SearchView’i nasıl ekleyeceğimizi öğrendik. Sonraki adımlarda kullanıcıdan aldığımız sorguyu nasıl saklayacağımızı ve arayacağımızı öğreneceğiz.</p><h3>2. <strong>Veri Depolamak ve Aramak</strong></h3><p>Bu adımda bir SQLite sanal tablosu oluşturacağız. Tablo’da kelimeler ve tanımları tutulacak. Tabloyu bir .txt dosyasıyla dolduracağız.</p><p><strong><em>Sanal Tablo Oluşturma</em></strong></p><p>Sanal tablo, SQLite tablosuna benzer şekilde davranır. Ancak bir veritabanı dosyası yerine geri çağrılar(callbacks) aracılığıyla <strong><em>bellekteki bir nesneyi okur ve yazar</em></strong>. Sanal tablo oluşturmak için <strong><em>DictionaryDatabase</em></strong> isminde bir sınıf oluşturuyoruz.</p><pre>public class DictionaryDatabase {<br>    ...<br>}</pre><p>DictionaryDatabase sınıfında SQLiteOpenHelper’dan türeyen <strong><em>DatabaseOpenHelper</em></strong> isminde bir iç sınıf(inner class) oluşturuyoruz. DatabaseOpenHelper sınıfını tabloyu oluşturmak(create table) ve gerektiğinde yükseltmek(upgrade) için kullanacağız.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5984a519837810049768667dc478139e/href">https://medium.com/media/5984a519837810049768667dc478139e/href</a></iframe><p><strong><em>Sanal Tabloyu Doldurma</em></strong></p><p>Artık tablomuza veri kaydedebiliriz. Bunun için yukarıda bahsettiğim gibi <strong><em>res/raw/definitions.txt</em></strong> dosyasından yararlanacağız. Dosyayı ve kodların tümünü yazının sonunda bulabilirsiniz. Aşağıdaki kod dosyayı nasıl parse edip satır satır sanal tabloya ekleyeceğimizi gösteriyor. <em>Tüm bunlar, kullanıcı arayüzünün kilitlenmesini önlemek için başka bir iş parçacığında yapılıyor.</em> Aşağıdaki kodu <strong><em>DatabaseOpenHelper</em></strong> inner sınıfına ekliyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b4525ebc665a2d79ef57f51654e35df/href">https://medium.com/media/9b4525ebc665a2d79ef57f51654e35df/href</a></iframe><p>Tabloyu doldurmak için yazmış olduğumuz <strong><em>loadDictionary()</em></strong> metodunu <em>DatabaseOpenHelper</em> sınıfının <strong><em>onCreate()</em></strong> metodunda çağırıyoruz.</p><pre>@Override<br>public void onCreate(SQLiteDatabase db) {<br>    database = db;<br>    database.execSQL(FTS_TABLE_CREATE);<br>    <strong>loadDictionary();</strong><br>}</pre><p><strong><em>Veri Sorgulama</em></strong></p><p>Tablodan veri sorgulamak için <em>SearchView</em>’den aldığımız arama terimini kullanıyoruz. Kullanıcının arama kutusuna girdiği sorguyu arayan bir SQL ifadesi oluşturmak için <strong><em>DictionaryDatabase</em></strong> sınıfına aşağıdaki metodları ekliyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adc13dee4aa5fa78f8bf4910a83b055a/href">https://medium.com/media/adc13dee4aa5fa78f8bf4910a83b055a/href</a></iframe><p><strong><em>getWordMatches()</em></strong> metodu tabloda sorguyu arıyor. Herhangi bir sonuç bulduğunda geriye <strong><em>Cursor </em></strong>döndürüyor.</p><h4>Content Provider Oluşturmak</h4><p>Bunun için aşağıdaki <strong><em>DictionaryProvider </em></strong>sınıfını yazıyoruz. Bu sınıfı dictionary veritabanına erişim sağlamak için kullanacağız.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc7670c461e7bdebe1eed01333849c30/href">https://medium.com/media/bc7670c461e7bdebe1eed01333849c30/href</a></iframe><p>Ardından bu sınıfı <strong><em>AndroidManifest</em></strong>’te tanıtıyoruz.</p><pre>...</pre><pre>&lt;provider android:name=&quot;<strong>.DictionaryProvider</strong>&quot;                  android:authorities=&quot;com.betulsahin.searchviewkullanimi.DictionaryProvider&quot; /&gt;<br>         <br>&lt;/application&gt;<br>&lt;/manifest&gt;</pre><p>Artık MainActivity’e ListView koyup sözcükleri gösterebiliriz !</p><p>İlk olarak <strong><em>activity_main.xml</em></strong> dosyasını aşağıdaki gibi düzenliyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7de9e8171bf3d3918cb05a42d7235863/href">https://medium.com/media/7de9e8171bf3d3918cb05a42d7235863/href</a></iframe><p>Ardından <a href="https://android.googlesource.com/platform/development/+/master/samples/SearchableDictionary/res/layout?autodive=0%2F%2F%2F%2F"><strong><em>layout</em></strong></a><strong><em>/result.xml</em> </strong>dosyasını ekliyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6535752862322d963398534c34f87c79/href">https://medium.com/media/6535752862322d963398534c34f87c79/href</a></iframe><p>Ve MainActivity onCreate() metodunda ilgili layoutları çağırıyoruz.</p><pre>mTextView = (TextView) findViewById(R.id.<em>text</em>);<br>mListView = (ListView) findViewById(R.id.<em>list</em>);</pre><p>Sözlükte arama yapmak ve verilen sorgu için sonuçları görüntülemek için aşağıdaki <strong><em>showResults()</em></strong> metodunu yazıyoruz. Bu metodu handleIntent() metodunda çağırıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fbd6923144eeebf74d4477dc2efa5bd/href">https://medium.com/media/0fbd6923144eeebf74d4477dc2efa5bd/href</a></iframe><p>Son olarak ListView’de herhangi bir sözcüğe tıklandığında başka bir sayfada açılması için <strong><em>showResults()</em></strong> metoduna aşağıdaki kodları ekliyoruz. Sözcüklere tıklandığında <strong><em>WordActivity</em></strong>’e gidecek ve sözcük detayları görüntülenecek.</p><pre>// Define the on-click listener for the list items<br>mListView.setOnItemClickListener(new OnItemClickListener() {<br>                <a href="http://twitter.com/Override">@Override</a><br>                public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {<br>                    // Build the Intent used to open WordActivity with a specific word Uri<br>                    Intent wordIntent = new Intent(getApplicationContext(), WordActivity.class);<br>                    Uri data = Uri.withAppendedPath(DictionaryProvider.CONTENT_URI,<br>                                                    String.valueOf(id));<br>                    wordIntent.setData(data);<br>                    startActivity(wordIntent);<br>                }<br>            });</pre><p><strong><em>WordActivity </em></strong>sınıfının kodlarını yazının sonunda paylaştığım repoda bulabilirsiniz.</p><h3>3. <strong>Geriye Doğru Uyumluluk</strong></h3><p>SearchView ve action bar yalnızca <em>Android 3.0</em> ve sonraki sürümlerde kullanılabilir. Eski platformları desteklemek için <em>search dialog</em>’a geri dönülebiliyor.</p><p><strong><em>Minimum ve Hedef API düzeylerini ayarlama</em></strong></p><p><em>Android developer dökümanında, search dialog</em>’u ayarlamak için, AndroidManifest’te aşağıdaki bildirimin yapılması söylenmiş. Bu bildirim yapıldığında, uygulamanın Android 3.0 veya sonraki sürümlerde eylem çubuğunu otomatik olarak kullanacağı ve eski cihazlarda geleneksel menü sistemini kullanacağı açıklanmış.</p><pre>&lt;uses-sdk android:minSdkVersion=&quot;7&quot; android:targetSdkVersion=&quot;15&quot; /&gt;<br><br>&lt;application&gt;<br>...</pre><p><strong><em>Eski Cihazlar için Search Dialog’un(Arama İletişim Kutusu) Desteklenmesi</em></strong></p><p>Eski cihazlarda search dialog’u çağırmak için, kullanıcı menüden arama menüsü öğesini seçtiğinde onSearchRequested() metodunu çağırıyoruz.</p><pre>@Override<br>public boolean onOptionsItemSelected(MenuItem item) {<br>    switch (item.getItemId()) {<br>        case R.id.search:<br>            <strong>onSearchRequested();</strong><br>            return true;<br>        default:<br>            return false;<br>    }<br>}</pre><p><strong><em>Çalışma Zamanında Android Derleme Sürümünün Kontrol Edilmesi</em></strong></p><p>Çalışma zamanında, eski cihazlarda desteklenmeyen bir <em>SearchView</em> kullanımının meydana gelmediğinden emin olmak için cihaz sürümünü aşağıdaki gibi kontrol edebilirsiniz.</p><pre>@Override<br>public boolean onCreateOptionsMenu(Menu menu) {<br><br>    MenuInflater inflater = getMenuInflater();<br>    inflater.inflate(R.menu.options_menu, menu);<br><br>    if (<strong>Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.HONEYCOMB</strong>) {<br>        SearchManager searchManager =<br>                (SearchManager) getSystemService(Context.SEARCH_SERVICE);<br>        SearchView searchView =<br>                (SearchView) menu.findItem(R.id.search).getActionView();<br>        searchView.setSearchableInfo(<br>                searchManager.getSearchableInfo(getComponentName()));<br>        searchView.setIconifiedByDefault(false);<br>    }<br>    return true;<br>}</pre><p>Uygulamamıza arama öğesi eklemeyi, verileri depolamak ve gerektiğinde sorgulayıp çekmek için sanal tablo kullanmayı öğrendik. Son olarak uygulamamızı eski sürümlerde desteklemek için gerekli düzenlemeleri yaptık.</p><p>Umarım faydalı olur.</p><p><strong>Referans Kaynaklar:</strong></p><p><a href="https://developer.android.com/training/search">Adding Search Functionality — developer.android.com</a> (Orjinal döküman)</p><p><a href="https://android.googlesource.com/platform/development/+/master/samples/SearchableDictionary">SearchableDictionary — android.googlesource.com</a> (Tüm kodlar)</p><p><a href="https://github.com/betul-sahin/android-searchview-kullanimi">Kaynak Kodlar: Anroid-Searchview-Kullanimi (Kelime önerisi getirme hariç kodlar)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=164c53417655" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>