Soalan Temuduga Spring Boot

1. Pengenalan

Sejak diperkenalkan, Spring Boot telah menjadi pemain utama dalam ekosistem Spring. Projek ini menjadikan kehidupan kita lebih mudah dengan kemampuan konfigurasi automatiknya.

Dalam tutorial ini, kita akan membahas beberapa soalan yang paling biasa berkaitan dengan Spring Boot yang mungkin muncul semasa temu duga kerja.

2. Soalan

S1. Apa itu Spring Boot dan Apa Ciri Utamanya?

Spring Boot pada asasnya adalah kerangka untuk pengembangan aplikasi yang cepat yang dibangun di atas Spring Framework. Dengan konfigurasi automatik dan sokongan pelayan aplikasi tertanam, digabungkan dengan dokumentasi yang luas dan sokongan komuniti yang dinikmati, Spring Boot adalah salah satu teknologi yang paling popular di ekosistem Java setakat ini.

Berikut adalah beberapa ciri penting:

  • Permulaan - sekumpulan keterangan ketergantungan untuk memasukkan kebergantungan yang relevan di mana sahaja
  • Konfigurasi automatik - cara untuk mengkonfigurasi aplikasi secara automatik berdasarkan kebergantungan yang terdapat di classpath
  • Penggerak - untuk mendapatkan ciri siap pengeluaran seperti pemantauan
  • Keselamatan
  • Pembalakan

S2. Apakah Perbezaan Antara Spring dan Spring Boot?

Spring Framework menyediakan pelbagai ciri yang menjadikan pengembangan aplikasi web lebih mudah. Ciri-ciri ini termasuk suntikan kebergantungan, pengikatan data, pengaturcaraan berorientasikan aspek, akses data, dan banyak lagi.

Selama bertahun-tahun, Spring telah berkembang semakin kompleks, dan jumlah konfigurasi yang diperlukan oleh aplikasi tersebut boleh menakutkan. Di sinilah Spring Boot sangat berguna - ini menjadikan konfigurasi aplikasi Spring menjadi mudah.

Pada dasarnya, sementara Spring tidak disokong, Spring Boot mengambil pandangan mengenai platform dan perpustakaan, membiarkan kami memulakan dengan cepat.

Berikut adalah dua faedah terpenting yang dibawa oleh Spring Boot:

  • Konfigurasi automatik aplikasi berdasarkan artifak yang dijumpainya di classpath
  • Berikan ciri-ciri tidak berfungsi yang biasa digunakan oleh aplikasi dalam pengeluaran, seperti pemeriksaan keselamatan atau kesihatan

Sila periksa salah satu tutorial kami yang lain untuk perbandingan terperinci antara Vanilla Spring dan Spring Boot.

S3. Bagaimana Kita Boleh Menyiapkan Aplikasi Spring Boot Dengan Maven?

Kita boleh memasukkan Spring Boot dalam projek Maven seperti mana yang berlaku di perpustakaan lain. Walau bagaimanapun, cara terbaik adalah mewarisi dari projek ibu bapa spring-boot-starter dan menyatakan pergantungan kepada pemula Spring Boot. Melakukan ini membolehkan projek kami menggunakan semula tetapan lalai Spring Boot.

Mewarisi projek induk musim semi-boot-starter mudah - kita hanya perlu menentukan elemen induk dalam pom.xml :

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

Kami boleh mendapatkan versi terkini spring-boot-starter-parent di Maven Central.

Menggunakan projek induk permulaan adalah mudah, tetapi tidak selalu dapat dilaksanakan. Sebagai contoh, jika syarikat kami memerlukan semua projek untuk mewarisi POM standard, kami masih boleh mendapat keuntungan dari pengurusan pergantungan Spring Boot menggunakan induk khusus.

S4. Apa itu Spring Initializr?

Spring Initializr adalah cara mudah untuk membuat projek Spring Boot.

Kita boleh pergi ke laman Spring Initializr, memilih alat pengurusan kebergantungan (baik Maven atau Gradle), bahasa (Java, Kotlin atau Groovy), skema pembungkusan (Jar atau Perang), versi dan pergantungan, dan memuat turun projek.

Ini membuat projek kerangka untuk kita dan menjimatkan masa penyediaan sehingga kita dapat menumpukan perhatian pada penambahan logik perniagaan.

Walaupun kita menggunakan wizard projek baru IDE kami (seperti STS atau Eclipse with STS plugin) untuk membuat projek Spring Boot, ia menggunakan Spring Initializr di bawah tudung.

S5. Permulaan Boot Musim Semi Apa yang Terdapat di Luar sana?

Setiap starter berperanan sebagai pusat sehenti untuk semua teknologi Spring yang kita perlukan. Pergantungan lain yang diperlukan kemudian ditarik secara sementara dan dikendalikan secara konsisten.

Semua pemula berada di bawah kumpulan org.springframework.boot dan nama mereka bermula dengan spring-boot-starter- . Corak penamaan ini menjadikannya mudah untuk mencari pemula, terutama ketika bekerja dengan IDE yang menyokong pergantungan pencarian berdasarkan nama.

Pada masa penulisan ini, terdapat lebih daripada 50 permulaan yang kami gunakan. Yang paling kerap digunakan adalah:

  • spring-boot-starter: starter teras, termasuk sokongan konfigurasi automatik, pembalakan, dan YAML
  • spring-boot-starter-aop: starter untuk pengaturcaraan berorientasikan aspek dengan Spring AOP dan AspectJ
  • spring-boot-starter-data-jpa: pemula untuk menggunakan Spring Data JPA dengan Hibernate
  • spring-boot-starter-security: pemula untuk menggunakan Spring Security
  • spring-boot-starter-test: pemula untuk menguji aplikasi Spring Boot
  • spring-boot-starter-web: pemula untuk membina laman web, termasuk RESTful, aplikasi menggunakan Spring MVC

Untuk senarai pemula yang lengkap, sila lihat repositori ini.

Untuk mendapatkan maklumat lebih lanjut mengenai Spring Boot permulaan, lihat Intro to Spring Boot Starters.

S6. Bagaimana Melumpuhkan Konfigurasi Auto Tertentu?

Sekiranya kami ingin menonaktifkan konfigurasi automatik tertentu, kami dapat menunjukkannya menggunakan atribut exclude dari anotasi @EnableAutoConfiguration . Contohnya, coretan kod ini meneutralkan DataSourceAutoConfiguration :

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

Sekiranya kami mengaktifkan konfigurasi automatik dengan anotasi @SpringBootApplication - yang mempunyai @EnableAutoConfiguration sebagai meta-anotasi - kami boleh mematikan konfigurasi automatik dengan atribut dengan nama yang sama:

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

Kami juga dapat mematikan konfigurasi automatik dengan sifat persekitaran spring.autoconfigure.exclude . Tetapan ini dalam fail application.properties melakukan perkara yang sama seperti sebelumnya:

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

S7. Bagaimana Mendaftar Konfigurasi Auto 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 menjadikannya mudah dan bersih, Spring mempunyai penyediaan profil, untuk membantu memisahkan konfigurasi untuk setiap persekitaran . Oleh itu, daripada mengekalkan program ini secara teratur, sifatnya dapat disimpan dalam fail berasingan seperti aplikasi-dev. sifat dan aplikasi-prod. harta benda . Lalai application.propertie mata s ke profil menggunakan kini aktif musim bunga. profil. aktif sehingga konfigurasi yang betul diambil.

Spring Profiles memberikan pandangan menyeluruh mengenai topik ini.

3. Kesimpulannya

Tutorial ini membahas beberapa soalan paling kritikal mengenai Spring Boot yang mungkin anda hadapi semasa temu ramah teknikal. Kami harap mereka dapat membantu anda melaksanakan tugas impian anda.