Preguntas de la entrevista de Spring Boot

1. Introducción

Desde su introducción, Spring Boot ha sido un jugador clave en el ecosistema Spring. Este proyecto nos hace la vida mucho más fácil con su capacidad de autoconfiguración.

En este tutorial, cubriremos algunas de las preguntas más comunes relacionadas con Spring Boot que pueden surgir durante una entrevista de trabajo.

2. Preguntas

Q1. ¿Qué es Spring Boot y cuáles son sus características principales?

Spring Boot es esencialmente un marco para el desarrollo rápido de aplicaciones construido sobre Spring Framework. Con su configuración automática y soporte de servidor de aplicaciones integrado, combinado con la extensa documentación y el soporte de la comunidad que disfruta, Spring Boot es una de las tecnologías más populares en el ecosistema de Java hasta la fecha.

Aquí hay algunas características destacadas:

  • Entrantes: un conjunto de descriptores de dependencia para incluir dependencias relevantes de una vez
  • Configuración automática: una forma de configurar automáticamente una aplicación según las dependencias presentes en la ruta de clases.
  • Actuador: para obtener funciones listas para la producción, como monitoreo
  • Seguridad
  • Inicio sesión

Q2. ¿Cuáles son las diferencias entre Spring y Spring Boot?

Spring Framework proporciona múltiples características que facilitan el desarrollo de aplicaciones web. Estas características incluyen inyección de dependencia, enlace de datos, programación orientada a aspectos, acceso a datos y muchas más.

A lo largo de los años, Spring se ha vuelto cada vez más compleja, y la cantidad de configuración que requiere dicha aplicación puede resultar intimidante. Aquí es donde Spring Boot es útil: hace que configurar una aplicación Spring sea muy fácil.

Esencialmente, mientras Spring no tiene opiniones, Spring Boot tiene una visión obstinada de la plataforma y las bibliotecas, lo que nos permite comenzar rápidamente.

Estos son dos de los beneficios más importantes que aporta Spring Boot:

  • Configure automáticamente las aplicaciones según los artefactos que encuentre en la ruta de clases
  • Proporcionar características no funcionales comunes a las aplicaciones en producción, como controles de seguridad o estado.

Consulte uno de nuestros otros tutoriales para obtener una comparación detallada entre Vanilla Spring y Spring Boot.

Q3. ¿Cómo podemos configurar una aplicación Spring Boot con Maven?

Podemos incluir Spring Boot en un proyecto de Maven como lo haríamos con cualquier otra biblioteca. Sin embargo, la mejor manera es heredar del proyecto spring-boot-starter-parent y declarar dependencias a los arrancadores Spring Boot. Hacer esto permite que nuestro proyecto reutilice la configuración predeterminada de Spring Boot.

Heredar el proyecto spring-boot-starter-parent es sencillo: solo necesitamos especificar un elemento principal en pom.xml :

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

Podemos encontrar la última versión de spring-boot-starter-parent en Maven Central.

Usar el proyecto principal inicial es conveniente, pero no siempre factible. Por ejemplo, si nuestra empresa requiere que todos los proyectos hereden de un POM estándar, aún podemos beneficiarnos de la gestión de dependencias de Spring Boot utilizando un padre personalizado.

Q4. ¿Qué es Spring Initializr?

Spring Initializr es una forma conveniente de crear un proyecto Spring Boot.

Podemos ir al sitio Spring Initializr, elegir una herramienta de gestión de dependencias (ya sea Maven o Gradle), un lenguaje (Java, Kotlin o Groovy), un esquema de empaquetado (Jar o War), versión y dependencias, y descargar el proyecto.

Esto crea un proyecto esqueleto para nosotros y ahorra tiempo de configuración para que podamos concentrarnos en agregar lógica empresarial.

Incluso cuando usamos nuestro asistente de proyecto nuevo de IDE (como STS o Eclipse con el complemento STS) para crear un proyecto Spring Boot, usa Spring Initializr bajo el capó.

Q5. ¿Qué arrancadores de arranque de primavera están disponibles?

Cada iniciador juega un papel como una ventanilla única para todas las tecnologías de Spring que necesitamos. A continuación, otras dependencias necesarias se incorporan de forma transitiva y se gestionan de forma coherente.

Todos los principiantes están bajo el grupo org.springframework.boot y sus nombres comienzan con spring-boot-starter- . Este patrón de nomenclatura facilita la búsqueda de iniciadores, especialmente cuando se trabaja con IDE que admiten la búsqueda de dependencias por nombre.

En el momento de escribir este artículo, hay más de 50 entrantes a nuestra disposición. Los más utilizados son:

  • spring-boot-starter: core starter, que incluye compatibilidad con la configuración automática, registro y YAML
  • spring-boot-starter-aop: iniciador para programación orientada a aspectos con Spring AOP y AspectJ
  • spring-boot-starter-data-jpa: iniciador para usar Spring Data JPA con Hibernate
  • spring-boot-starter-security: iniciador para usar Spring Security
  • spring-boot-starter-test: iniciador para probar aplicaciones Spring Boot
  • spring-boot-starter-web: iniciador para la creación de aplicaciones web, incluidas RESTful, que usan Spring MVC

Para obtener una lista completa de principiantes, consulte este repositorio.

Para encontrar más información sobre los arrancadores Spring Boot, eche un vistazo a Introducción a los arrancadores Spring Boot.

Q6. ¿Cómo deshabilitar una configuración automática específica?

Si queremos deshabilitar una autoconfiguración específica, podemos indicarlo usando el atributo exclude de la anotación @EnableAutoConfiguration . Por ejemplo, este fragmento de código neutraliza DataSourceAutoConfiguration :

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

Si habilitamos la configuración automática con la anotación @SpringBootApplication , que tiene @EnableAutoConfiguration como meta-anotación, podríamos deshabilitar la configuración automática con un atributo del mismo nombre:

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

También podemos deshabilitar una configuración automática con la propiedad de entorno spring.autoconfigure.exclude . Esta configuración en el archivo application.properties hace lo mismo que antes:

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

Q7. ¿Cómo registrar una configuración automática personalizada?

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.

Para hacer esto fácil y limpio, Spring tiene la provisión de perfiles, para ayudar a separar la configuración de cada ambiente . De modo que en lugar de mantener esto mediante programación, las propiedades se pueden guardar en archivos separados como application-dev. propiedades y aplicación-prod. propiedades . El application.propertie s predeterminado apunta al perfil activo actualmente usando Spring. Perfiles activo para que se recoja la configuración correcta.

Spring Profiles ofrece una visión completa de este tema.

3. Conclusión

Este tutorial repasó algunas de las preguntas más críticas sobre Spring Boot que puede enfrentar durante una entrevista técnica. Esperamos que le ayuden a conseguir el trabajo de sus sueños.