Spring Boot ile rest servis isteklerine cevap verebilecek bir java uygulaması geliştireceğiz.
Uygulamamızın iskeletini ve kütüphanelerini yönetmek için Gradle kullanacağız.Şu link üzerinden inceleyebilirsiniz
keramiozsoy.wordpress.com/gradle
Terminalimizi açıp çalışma alanımıza gidelim.
/home/user/workarea/spring-boot-sample
Java dosyalarının bulunacağı klasörlerimizi oluşturalım.
mkdir -p src/main/java/hello
Uygulamamızda iki adet java sınıfı olacak.
App.java sınıfı projemizi ayağa kaldırmamızı sağlarken, NameController.java sınıfı istekleri karşılayacak olan url bilgisini ve metottan dönmesi gereken işlemleri yapıp dönecek.
Projede kullanılan bazı noktaları açıklayalım.
@SpringBootApplication >>
Uygulamamızın başlangıç noktası için gereklidir.
@RestController = @Controller + @ResponseBody >>
Controller ile koda gelen istekleri alacağımız sınıfları işaretliyor, ResponseBody ile metodları işaretliyorduk. Artık RestController ile ortak bir yerden bunu kontrol ediyor ve bize json formatında veri dönmesini sağlıyor.
@RequestMapping >>
Url belirliyoruz.
Sınıflara bakalım.
App.java
package hello; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
NameController.java
package hello; import java.util.concurrent.atomic.AtomicLong; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class NameController { private static final String template = "Hello, %s!"; private final AtomicLong counter = new AtomicLong(); @RequestMapping("/") public String home(){ return "home :)"; } @RequestMapping("/sendName") public String sendName(@RequestParam(value="nameParam", defaultValue="Noo!!") String name) { return counter.incrementAndGet() + " - " + String.format(template, name); } }
Projemizi gradle ile çalıştırabilmek için build.gradle dosyasını oluşturmalıyız.
Oluşturduktan sonra projemizin ağaç yapısı aşağıdaki şekildedir.
spring-boot-sample ├── build.gradle └── src └── main └── java └── hello ├── App.java └── NameController.java
Peki build.gradle dosyasına içerisinde spring boot uygulaması geliştirebilmek için eklemiz gerekenlere bakalım.
Gradle ile pluginleri yönetmek için plugin lerin bulunduğu site üzerinden springframework yazarak bağımlılıkları buluyoruz.
https://plugins.gradle.org
pluginimizin ismi aşağıdadır.
org.springframework.boot
Bağımlılıkları ekleyelim.
build.gradle
buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.2.RELEASE") } } apply plugin: 'org.springframework.boot'
Öncekilere ek olarak uygulamamız java uygulaması olduğu için gerekli plugin ekliyoruz.
apply plugin : 'java'
Uygulamamıza rest uygulaması olarak çalışabilmesi için gerekli plugin ekliyoruz.
apply plugin: 'io.spring.dependency-management' repositories { mavenCentral() } dependencies { compile("org.springframework.boot:spring-boot-starter-web") }
Peki spring-boot-starter-web isimli bağımlılık nedir ? Ne işe yarar?
Spring framework bir çok alt module sahip bir çatıdır. Bu modullerden biri spring-boot-starter-web dir. Bu modul projemizi tek başına sunucu kurulumu yapılmadan kullanabilmeyi ve isteklere cevap vermeyi sağlar. Uygulamamıza eklemek istediğimiz özelikleri tek tek bu şekilde ekleyebilirsiniz. Peki bunlar nereden öğrenebiliriz
Spring boot github hesabından bakabiliriz.
https://github.com/spring-projects/spring-boot/tree/master/spring-boot-project/spring-boot-starters
Bu adımları yaptıktan sonra uygulamamız derlendikten sonra jar dosyası üretilecek ama biz bu ismi özelleştirmek istiyorsak şu eklemeyi yapabiliriz.Fakat zorunlu değildir.
bootJar { baseName = 'app' version = '0.0.1' }
Hadi projemizi derleyip çalıştıralım.
build.gradle dosyasının bulunduğu dizin içerisinde şu komutları çalıştırabiliriz.
gradle bootrun
veya
gradle build java -jar build/libs/app-0.0.1.jar
Komut Çıktısı:
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.2.RELEASE) 2018-05-11 07:50:10.440 INFO 7542 --- [ main] hello.App : Starting App on host with PID 7542 (/home/user/workarea/spring-boot-sample/build/libs/app-0.0.1.jar started by root in /home/user/workarea/spring-boot-sample) 2018-05-11 07:50:10.448 INFO 7542 --- [ main] hello.App : No active profile set, falling back to default profiles: default 2018-05-11 07:50:10.598 INFO 7542 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@1e1023e: startup date [Fri May 11 07:50:10 EDT 2018]; root of context hierarchy 2018-05-11 07:50:12.299 INFO 7542 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2018-05-11 07:50:12.355 INFO 7542 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2018-05-11 07:50:12.355 INFO 7542 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.31 2018-05-11 07:50:12.384 INFO 7542 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib/i386:/lib:/usr/lib] 2018-05-11 07:50:12.513 INFO 7542 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2018-05-11 07:50:12.513 INFO 7542 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1923 ms 2018-05-11 07:50:12.738 INFO 7542 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/] 2018-05-11 07:50:12.741 INFO 7542 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2018-05-11 07:50:12.741 INFO 7542 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2018-05-11 07:50:12.741 INFO 7542 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2018-05-11 07:50:12.741 INFO 7542 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2018-05-11 07:50:12.979 INFO 7542 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2018-05-11 07:50:13.310 INFO 7542 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@1e1023e: startup date [Fri May 11 07:50:10 EDT 2018]; root of context hierarchy 2018-05-11 07:50:13.439 INFO 7542 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/sendName]}" onto public java.lang.String hello.NameController.sendName(java.lang.String) 2018-05-11 07:50:13.444 INFO 7542 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String hello.NameController.home() 2018-05-11 07:50:13.453 INFO 7542 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) 2018-05-11 07:50:13.453 INFO 7542 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest) 2018-05-11 07:50:13.514 INFO 7542 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2018-05-11 07:50:13.515 INFO 7542 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2018-05-11 07:50:13.745 INFO 7542 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2018-05-11 07:50:13.819 INFO 7542 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2018-05-11 07:50:13.821 INFO 7542 --- [ main] hello.App : Started App in 4.114 seconds (JVM running for 4.644)
Bu komutlar bize hazır Tomcat sunucusu ayağa kaldırıp 8080 portundan istekleri beklemesini sağladı.
Tarayıcımız açalım ve istek gönderelim.
http://localhost:8080/
Çıktı :
home 🙂
http://localhost:8080/sendName?nameParam=kerami
1 – Hello, kerami!
Artık isteklerimize cevap veren bir uygulamaya sahip olduk.
Github Link
https://github.com/keramiozsoy/spring-boot-samples/tree/master/spring-boot-sample
Teşekkürler, İyi Çalışmalar 🙂
Yorum bırakın