Pertanyaan Wawancara Spring Boot

1. Perkenalan

Sejak diperkenalkan, Spring Boot telah menjadi pemain kunci dalam ekosistem Spring. Proyek ini membuat hidup kita jauh lebih mudah dengan kemampuan konfigurasi otomatisnya.

Dalam tutorial ini, kami akan membahas beberapa pertanyaan paling umum yang berhubungan dengan Spring Boot yang mungkin muncul selama wawancara kerja.

2. Pertanyaan

P1. Apa itu Spring Boot dan Apa Fitur Utama?

Spring Boot pada dasarnya adalah kerangka kerja untuk pengembangan aplikasi cepat yang dibangun di atas Kerangka Spring. Dengan konfigurasi otomatis dan dukungan server aplikasi tertanam, dikombinasikan dengan dokumentasi ekstensif dan dukungan komunitas yang dinikmati, Spring Boot adalah salah satu teknologi paling populer di ekosistem Java saat ini.

Berikut beberapa fitur yang menonjol:

  • Pemula - sekumpulan deskriptor dependensi untuk menyertakan dependensi yang relevan kapan saja
  • Konfigurasi otomatis - cara untuk secara otomatis mengkonfigurasi aplikasi berdasarkan dependensi yang ada di classpath
  • Aktuator - untuk mendapatkan fitur siap produksi seperti pemantauan
  • Keamanan
  • Logging

P2. Apa Perbedaan Antara Spring dan Spring Boot?

Framework Spring menyediakan banyak fitur yang membuat pengembangan aplikasi web lebih mudah. Fitur-fitur ini mencakup injeksi ketergantungan, pengikatan data, pemrograman berorientasi aspek, akses data, dan banyak lagi.

Selama bertahun-tahun, Spring telah berkembang menjadi semakin kompleks, dan jumlah konfigurasi yang dibutuhkan aplikasi semacam itu dapat menakutkan. Di sinilah Spring Boot sangat berguna - membuat konfigurasi aplikasi Spring menjadi mudah.

Pada dasarnya, meskipun Spring tidak beropini, Spring Boot mengambil pandangan beropini dari platform dan pustaka, memungkinkan kami memulai dengan cepat.

Berikut adalah dua manfaat terpenting yang dibawa Spring Boot:

  • Konfigurasi otomatis aplikasi berdasarkan artefak yang ditemukannya di classpath
  • Menyediakan fitur non-fungsional yang umum untuk aplikasi dalam produksi, seperti keamanan atau health check

Silakan periksa salah satu tutorial kami yang lain untuk perbandingan mendetail antara vanilla Spring dan Spring Boot.

P3. Bagaimana Cara Mengatur Aplikasi Spring Boot Dengan Maven?

Kami dapat menyertakan Spring Boot dalam proyek Maven seperti yang kami lakukan di perpustakaan lainnya. Namun, cara terbaik adalah dengan mewarisi dari proyek spring-boot-starter-parent dan mendeklarasikan dependensi ke permulaan Spring Boot. Melakukan ini memungkinkan proyek kami menggunakan kembali pengaturan default Spring Boot.

Mewarisi proyek spring-boot-starter-parent sangatlah mudah - kita hanya perlu menentukan elemen induk di pom.xml :

 org.springframework.boot spring-boot-starter-parent 2.3.0.RELEASE 

Kita dapat menemukan versi terbaru dari spring-boot-starter-parent di Maven Central.

Menggunakan proyek induk awal memang nyaman, tetapi tidak selalu memungkinkan. Misalnya, jika perusahaan kami mengharuskan semua proyek untuk mewarisi dari POM standar, kami masih dapat memanfaatkan manajemen ketergantungan Spring Boot menggunakan induk khusus.

P4. Apa itu Spring Initializr?

Spring Initializr adalah cara mudah untuk membuat proyek Spring Boot.

Kita bisa pergi ke situs Spring Initializr, memilih alat manajemen ketergantungan (baik Maven atau Gradle), bahasa (Java, Kotlin atau Groovy), skema pengemasan (Jar atau Perang), versi dan ketergantungan, dan mengunduh proyek.

Ini membuat proyek kerangka untuk kami dan menghemat waktu penyiapan sehingga kami dapat berkonsentrasi pada penambahan logika bisnis.

Bahkan ketika kami menggunakan wizard proyek baru IDE (seperti STS atau Eclipse dengan plugin STS) untuk membuat proyek Spring Boot, program ini menggunakan Spring Initializr di bawah tenda.

P5. Apa Pemula Spring Boot Yang Tersedia di Luar Sana?

Setiap pemula berperan sebagai toko serba ada untuk semua teknologi Musim Semi yang kami butuhkan. Dependensi lain yang diperlukan kemudian ditarik masuk dan dikelola dengan cara yang konsisten.

Semua pemula berada di bawah grup org.springframework.boot dan namanya dimulai dengan spring-boot-starter- . Pola penamaan ini memudahkan untuk menemukan permulaan, terutama saat bekerja dengan IDE yang mendukung pencarian dependensi berdasarkan nama.

Pada saat penulisan ini, ada lebih dari 50 permulaan yang kami miliki. Yang paling umum digunakan adalah:

  • spring-boot-starter: starter inti, termasuk dukungan konfigurasi otomatis, logging, dan YAML
  • spring-boot-starter-aop: starter untuk pemrograman berorientasi aspek dengan Spring AOP dan AspectJ
  • spring-boot-starter-data-jpa: starter untuk menggunakan Spring Data JPA dengan Hibernate
  • spring-boot-starter-security: starter untuk menggunakan Spring Security
  • spring-boot-starter-test: starter untuk menguji aplikasi Spring Boot
  • spring-boot-starter-web: starter untuk membangun web, termasuk RESTful, aplikasi yang menggunakan Spring MVC

Untuk daftar lengkap pemula, silakan lihat repositori ini.

Untuk menemukan informasi lebih lanjut tentang permulaan Spring Boot, lihat Intro to Spring Boot Starters.

P6. Bagaimana Menonaktifkan Konfigurasi Otomatis Tertentu?

Jika kami ingin menonaktifkan konfigurasi otomatis tertentu, kami dapat menunjukkannya menggunakan atribut exclude dari anotasi @EnableAutoConfiguration . Misalnya, cuplikan kode ini menetralkan DataSourceAutoConfiguration :

// other annotations @EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class) public class MyConfiguration { }

Jika kita mengaktifkan konfigurasi otomatis dengan anotasi @SpringBootApplication - yang memiliki @EnableAutoConfiguration sebagai meta-annotation - kita dapat menonaktifkan konfigurasi otomatis dengan atribut dengan nama yang sama:

// other annotations @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) public class MyConfiguration { }

Kita juga dapat menonaktifkan konfigurasi otomatis dengan properti lingkungan spring.autoconfigure.exclude . Pengaturan dalam file application.properties ini melakukan hal yang sama seperti sebelumnya:

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

P7. Bagaimana cara Mendaftarkan Konfigurasi Otomatis Kustom?

To register an auto-configuration class, we must have its fully-qualified name listed under the EnableAutoConfiguration key in the META-INF/spring.factories file:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.baeldung.autoconfigure.CustomAutoConfiguration

If we build a project with Maven, that file should be placed in the resources/META-INF directory, which will end up in the mentioned location during the package phase.

Q8. How to Tell an Auto-Configuration to Back Away When a Bean Exists?

To instruct an auto-configuration class to back off when a bean is already existent, we can use the @ConditionalOnMissingBean annotation. The most noticeable attributes of this annotation are:

  • value: The types of beans to be checked
  • name: The names of beans to be checked

When placed on a method adorned with @Bean, the target type defaults to the method's return type:

@Configuration public class CustomConfiguration { @Bean @ConditionalOnMissingBean public CustomService service() { ... } }

Q9. How to Deploy Spring Boot Web Applications as Jar and War Files?

Traditionally, we package a web application as a WAR file, then deploy it into an external server. Doing this allows us to arrange multiple applications on the same server. During the time that CPU and memory were scarce, this was a great way to save resources.

However, things have changed. Computer hardware is fairly cheap now, and the attention has turned to server configuration. A small mistake in configuring the server during deployment may lead to catastrophic consequences.

Spring tackles this problem by providing a plugin, namely spring-boot-maven-plugin, to package a web application as an executable JAR. To include this plugin, just add a plugin element to pom.xml:

 org.springframework.boot spring-boot-maven-plugin 

With this plugin in place, we'll get a fat JAR after executing the package phase. This JAR contains all the necessary dependencies, including an embedded server. Thus, we no longer need to worry about configuring an external server.

We can then run the application just like we would an ordinary executable JAR.

Notice that the packaging element in the pom.xml file must be set to jar to build a JAR file:

jar

If we don't include this element, it also defaults to jar.

In case we want to build a WAR file, change the packaging element to war:

war

And leave the container dependency off the packaged file:

 org.springframework.boot spring-boot-starter-tomcat provided 

After executing the Maven package phase, we'll have a deployable WAR file.

Q10. How to Use Spring Boot for Command Line Applications?

Just like any other Java program, a Spring Boot command line application must have a main method. This method serves as an entry point, which invokes the SpringApplication#run method to bootstrap the application:

@SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class); // other statements } }

The SpringApplication class then fires up a Spring container and auto-configures beans.

Notice we must pass a configuration class to the run method to work as the primary configuration source. By convention, this argument is the entry class itself.

After calling the run method, we can execute other statements as in a regular program.

Q11. What Are Possible Sources of External Configuration?

Spring Boot provides support for external configuration, allowing us to run the same application in various environments. We can use properties files, YAML files, environment variables, system properties, and command-line option arguments to specify configuration properties.

We can then gain access to those properties using the @Value annotation, a bound object via the @ConfigurationProperties annotation, or the Environment abstraction.

Q12. What Does it Mean that Spring Boot Supports Relaxed Binding?

Relaxed binding in Spring Boot is applicable to the type-safe binding of configuration properties.

With relaxed binding, the key of a property doesn't need to be an exact match of a property name. Such an environment property can be written in camelCase, kebab-case, snake_case, or in uppercase with words separated by underscores.

For example, if a property in a bean class with the @ConfigurationProperties annotation is named myProp, it can be bound to any of these environment properties: myProp, my-prop, my_prop, or MY_PROP.

Q13. What is Spring Boot Devtools Used For?

Spring Boot Developer Tools, or DevTools, is a set of tools making the development process easier. To include these development-time features, we just need to add a dependency to the pom.xml file:

 org.springframework.boot spring-boot-devtools 

The spring-boot-devtools module is automatically disabled if the application runs in production. The repackaging of archives also excludes this module by default. Hence, it won't bring any overhead to our final product.

By default, DevTools applies properties suitable to a development environment. These properties disable template caching, enable debug logging for the web group, and so on. As a result, we have this sensible development-time configuration without setting any properties.

Applications using DevTools restart whenever a file on the classpath changes. This is a very helpful feature in development, as it gives quick feedback for modifications.

By default, static resources, including view templates, don't set off a restart. Instead, a resource change triggers a browser refresh. Notice this can only happen if the LiveReload extension is installed in the browser to interact with the embedded LiveReload server that DevTools contains.

For further information on this topic, please see Overview of Spring Boot DevTools.

Q14. How to Write Integration Tests?

When running integration tests for a Spring application, we must have an ApplicationContext.

To make our life easier, Spring Boot provides a special annotation for testing – @SpringBootTest. This annotation creates an ApplicationContext from configuration classes indicated by its classes attribute.

In case the classes attribute isn't set, Spring Boot searches for the primary configuration class. The search starts from the package containing the test up until it finds a class annotated with @SpringBootApplication or @SpringBootConfiguration.

For detailed instructions, check out our tutorial on testing in Spring Boot.

Q15. What Is Spring Boot Actuator Used For?

Essentially, Actuator brings Spring Boot applications to life by enabling production-ready features. These features allow us to monitor and manage applications when they're running in production.

Integrating Spring Boot Actuator into a project is very simple. All we need to do is to include the spring-boot-starter-actuator starter in the pom.xml file:

 org.springframework.boot spring-boot-starter-actuator 

Spring Boot Actuator can expose operational information using either HTTP or JMX endpoints. Most applications go for HTTP, though, where the identity of an endpoint and the /actuator prefix form a URL path.

Here are some of the most common built-in endpoints Actuator provides:

  • env: Exposes environment properties
  • health: Shows application health information
  • httptrace: Displays HTTP trace information
  • info: Displays arbitrary application information
  • metrics: Shows metrics information
  • loggers: Shows and modifies the configuration of loggers in the application
  • mappings: Displays a list of all @RequestMapping paths

Please refer to our Spring Boot Actuator tutorial for a detailed rundown.

Q16. Which Is a Better Way to Configure a Spring Boot Project – Using Properties or YAML?

YAML offers many advantages over properties files, such as:

  • More clarity and better readability
  • Perfect for hierarchical configuration data, which is also represented in a better, more readable format
  • Support for maps, lists, and scalar types
  • Can include several profiles in the same file

However, writing it can be a little difficult and error-prone due to its indentation rules.

For details and working samples, please refer to our Spring YAML vs Properties tutorial.

Q17. What Are the Basic Annotations that Spring Boot Offers?

The primary annotations that Spring Boot offers reside in its org.springframework.boot.autoconfigure and its sub-packages. Here are a couple of basic ones:

  • @EnableAutoConfiguration – to make Spring Boot look for auto-configuration beans on its classpath and automatically apply them.
  • @SpringBootApplication – used to denote the main class of a Boot Application. This annotation combines @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations with their default attributes.

Spring Boot Annotations offers more insight into the subject.

Q18. How Can You Change the Default Port in Spring Boot?

We can change the default port of a server embedded in Spring Boot using one of these ways:

  • using a properties file – we can define this in an application.properties (or application.yml) file using the property server.port
  • programmatically – in our main @SpringBootApplication class, we can set the server.port on the SpringApplication instance
  • using the command line – when running the application as a jar file, we can set the server.port as a java command argument:
    java -jar -Dserver.port=8081 myspringproject.jar 

Q19. Which Embedded Servers does Spring Boot Support, and How to Change the Default?

As of date, Spring MVC supports Tomcat, Jetty, and Undertow. Tomcat is the default application server supported by Spring Boot's web starter.

Spring WebFlux supports Reactor Netty, Tomcat, Jetty, and Undertow with Reactor Netty as default.

In Spring MVC, to change the default, let's say to Jetty, we need to exclude Tomcat and include Jetty in the dependencies:

 org.springframework.boot spring-boot-starter-web   org.springframework.boot spring-boot-starter-tomcat     org.springframework.boot spring-boot-starter-jetty 

Similarly, to change the default in WebFlux to UnderTow, we need to exclude Reactor Netty and include UnderTow in the dependencies.

“Comparing embedded servlet contains in Spring Boot” contains more details on the different embedded servers we can use with Spring MVC.

Q20. Why Do We Need Spring Profiles?

When developing applications for the enterprise, we typically deal with multiple environments such as Dev, QA, and Prod. The configuration properties for these environments are different.

For example, we might be using an embedded H2 database for Dev, but Prod could have the proprietary Oracle or DB2. Even if the DBMS is the same across environments, the URLs would definitely be different.

Untuk membuatnya mudah dan bersih, Spring memiliki penyediaan profil, untuk membantu memisahkan konfigurasi untuk setiap lingkungan . Sehingga alih-alih mempertahankan ini secara terprogram, properti dapat disimpan dalam file terpisah seperti application-dev. properti dan aplikasi-prod. properti . Aplikasi default.propertie s menunjuk ke profil yang sedang aktif menggunakan pegas. profil. aktif sehingga konfigurasi yang benar diambil.

Profil Musim Semi memberikan pandangan komprehensif tentang topik ini.

3. Kesimpulan

Tutorial ini membahas beberapa pertanyaan paling kritis tentang Spring Boot yang mungkin Anda hadapi selama wawancara teknis. Kami berharap mereka akan membantu Anda mendapatkan pekerjaan impian Anda.