STS (Spring Tool Suite ) kurulması gerekiyor. (Eclipse veya diğer editörlerle de yapılabilir ancak STS ile yapmak daha kolaydır)
STS de New->Spring Starter Project seçilir ve proje adı, maven için gerekli olan bilgiler girilir. Bir sonraki bölümde hangi modülleri kullanacağını seçeceğin bir liste gelecektir. Biz sadece Web seçiyoruz. Proje bu şekilde yaratılması bir Web projesi için yeterlidir
Bu projede pom.xml dosyasında aşağıdakini bağımlılıklar eklenmiş olmalı :
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Bu şekilde bir web projesi için gerekli olan kütüphanelerin hepsi yüklenecektir. Aynı zamanda test için gerekli olan kütüphanelerde yüklenmiş olur.
Aşağıdaki gibi bir ana sınıfı yaratılmış olacaktır:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Test kodu da aşağıdaki gibi üretilecektir:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
@WebAppConfiguration
public class DemoApplicationTests {
@Test
public void contextLoads() {
}
}
/hello şeklinde çağrıldığında "Hello World!" dönecek şekilde bir servis eklemek için ana uygulama sınıfını aşağıdaki gibi değiştirebiliriz:
@SpringBootApplication
@Controller
public class DemoApplication {
@RequestMapping("/hello")
@ResponseBody
String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Bu kod aşağıdaki gibi test edilebilir:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
@WebAppConfiguration
public class DemoApplicationTests {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setup() throws Exception {
this.mockMvc = webAppContextSetup(webApplicationContext).build();
}
@Test
public void testHello() throws Exception {
mockMvc.perform(get("/hello")).andExpect(content().string("Hello World!"));
}
}