봄 프레임 워크 인터뷰 질문

이 기사는 시리즈의 일부입니다. • Java Collections 인터뷰 질문

• 자바 타입 시스템 인터뷰 질문

• Java 동시성 인터뷰 질문 (+ 답변)

• Java 클래스 구조 및 초기화 면접 질문

• 자바 8 인터뷰 질문 (+ 답변)

• 자바 인터뷰 질문의 메모리 관리 (+ 답변)

• Java Generics 인터뷰 질문 (+ 답변)

• Java Flow Control 인터뷰 질문 (+ 답변)

• Java 예외 인터뷰 질문 (+ 답변)

• Java Annotations 인터뷰 질문 (+ 답변)

• Spring Framework 인터뷰 질문 (현재 기사)

목차

  • 1. 소개
  • 2. 스프링 코어
  • Q1. 스프링 프레임 워크 란?
  • Q2. Spring 사용의 이점은 무엇입니까?
  • Q3. 어떤 봄 하위 ​​프로젝트를 알고 있습니까? 간략하게 설명하십시오.
  • Q4. 의존성 주입이란?
  • Q5. 봄에 콩을 어떻게 주입 할 수 있습니까?
  • Q6. 콩을 주입하는 가장 좋은 방법은 무엇이며 왜
  • Q7. Beanfactory와 Applicationcontext의 차이점은 무엇입니까?
  • Q8. 스프링 빈이 란?
  • Q9. Spring Framework의 기본 Bean 범위는 무엇입니까?
  • Q10. Bean의 범위를 정의하는 방법은 무엇입니까?
  • Q11. 싱글 톤 빈은 스레드로부터 안전한가요?
  • Q12. Spring Bean 라이프 사이클은 어떻게 생겼습니까?
  • Q13. Spring Java 기반 구성이란 무엇입니까?
  • Q14. 하나의 프로젝트에 여러 Spring 구성 파일을 가질 수 있습니까?
  • Q15. 스프링 보안이란?
  • Q16. 스프링 부트 란?
  • Q17. Spring Framework에서 사용되는 디자인 패턴의 이름을 지정하십시오.
  • Q18. 스코프 프로토 타입은 어떻게 작동합니까?
  • 3. 스프링 웹 MVC
  • Q19. Spring Bean에서 Servletcontext 및 Servletconfig 객체를 얻는 방법은 무엇입니까?
  • Q20. Spring Mvc의 컨트롤러는 무엇입니까?
  • Q21. @Requestmapping 주석은 어떻게 작동합니까?
  • 4. 스프링 데이터 접근
  • Q22. Spring Jdbctemplate 클래스는 무엇이며 어떻게 사용합니까?
  • Q23. 봄에 거래를 어떻게 활성화하고 그 이점은 무엇입니까?
  • Q24. Spring Dao는 무엇입니까?
  • 5. Spring Aspect-Oriented Programming (AOP)
  • Q25. Aspect-Oriented Programming이란 무엇입니까?
  • Q26. Aop에서 Aspect, Advice, Pointcut 및 Joinpoint는 무엇입니까?
  • Q27. 위빙이란?
  • 6. 봄 5
  • Q28. 반응 형 프로그래밍이란?
  • Q29. Spring Webflux 란?
  • Q30. 모노 및 플럭스 유형은 무엇입니까?
  • Q31. Webclient 및 Webtestclient의 용도는 무엇입니까?
  • Q32. 리 액티브 스트림 사용의 단점은 무엇입니까?
  • Q33. Spring 5는 이전 버전의 Java와 호환됩니까?
  • Q34. Ow Spring 5가 Jdk 9 모듈 성과 어떻게 통합됩니까?
  • Q35. 동일한 애플리케이션에서 Web Mvc와 Webflux를 모두 사용할 수 있습니까?
  • 7. 결론

1. 소개

이 기사에서는 면접 중에 나타날 수있는 가장 일반적인 Spring 관련 질문 중 일부를 살펴볼 것입니다.

2. 스프링 코어

Q1. 스프링 프레임 워크 란?

Spring은 Java Enterprise Edition 애플리케이션 개발에 가장 널리 사용되는 프레임 워크입니다. Spring의 핵심 기능은 모든 Java 애플리케이션 개발에 사용할 수 있습니다.

Jakarta EE 플랫폼 위에 다양한 웹 애플리케이션을 빌드하기 위해 확장을 사용할 수도 있고 단순한 독립형 애플리케이션에서 종속성 주입 프로비저닝을 사용할 수도 있습니다.

Q2. Spring을 사용하면 어떤 이점이 있습니까?

자카르타 EE 개발을 더 쉽게 만드는 Spring 목표. 사용의 장점은 다음과 같습니다.

  • Lightweight: there is a slight overhead of using the framework in development
  • Inversion of Control (IoC): Spring container takes care of wiring dependencies of various objects, instead of creating or looking for dependent objects
  • Aspect Oriented Programming (AOP): Spring supports AOP to separate business logic from system services
  • IoC container: it manages Spring Bean life cycle and project specific configurations
  • MVC framework: that is used to create web applications or RESTful web services, capable of returning XML/JSON responses
  • Transaction management: reduces the amount of boiler-plate code in JDBC operations, file uploading, etc., either by using Java annotations or by Spring Bean XML configuration file
  • Exception Handling: Spring provides a convenient API for translating technology-specific exceptions into unchecked exceptions

Q3. What Spring Sub-Projects Do You Know? Describe Them Briefly.

  • Core – a key module that provides fundamental parts of the framework, like IoC or DI
  • JDBC – this module enables a JDBC-abstraction layer that removes the need to do JDBC coding for specific vendor databases
  • ORM integration – provides integration layers for popular object-relational mapping APIs, such as JPA, JDO, and Hibernate
  • Web – a web-oriented integration module, providing multipart file upload, Servlet listeners, and web-oriented application context functionalities
  • MVC framework – a web module implementing the Model View Controller design pattern
  • AOP module – aspect-oriented programming implementation allowing the definition of clean method-interceptors and pointcuts

Q4. What Is Dependency Injection?

Dependency Injection, an aspect of Inversion of Control (IoC), is a general concept stating that you do not create your objects manually but instead describe how they should be created. An IoC container will instantiate required classes if needed.

For more details, please refer here.

Q5. How Can We Inject Beans in Spring?

A few different options exist:

  • Setter Injection
  • Constructor Injection
  • Field Injection

The configuration can be done using XML files or annotations.

For more details, check this article.

Q6. Which Is the Best Way of Injecting Beans and Why?

The recommended approach is to use constructor arguments for mandatory dependencies and setters for optional ones. Constructor injection allows injecting values to immutable fields and makes testing easier.

Q7. What Is the Difference Between Beanfactory and Applicationcontext?

BeanFactory is an interface representing a container that provides and manages bean instances. The default implementation instantiates beans lazily when getBean() is called.

ApplicationContext is an interface representing a container holding all information, metadata, and beans in the application. It also extends the BeanFactory interface but the default implementation instantiates beans eagerly when the application starts. This behavior can be overridden for individual beans.

For all differences, please refer to the reference.

Q8. What Is a Spring Bean?

The Spring Beans are Java Objects that are initialized by the Spring IoC container.

Q9. What Is the Default Bean Scope in Spring Framework?

By default, a Spring Bean is initialized as a singleton.

Q10. How to Define the Scope of a Bean?

To set Spring Bean's scope, we can use @Scope annotation or “scope” attribute in XML configuration files. There are five supported scopes:

  • singleton
  • prototype
  • request
  • session
  • global-session

For differences, please refer here.

Q11. Are Singleton Beans Thread-Safe?

No, singleton beans are not thread-safe, as thread safety is about execution, whereas the singleton is a design pattern focusing on creation. Thread safety depends only on the bean implementation itself.

Q12. What Does the Spring Bean Lifecycle Look Like?

First, a Spring bean needs to be instantiated, based on Java or XML bean definition. It may also be required to perform some initialization to get it into a usable state. After that, when the bean is no longer required, it will be removed from the IoC container.

The whole cycle with all initialization methods is shown on the image (source):

Q13. What Is the Spring Java-Based Configuration?

It's one of the ways of configuring Spring-based applications in a type-safe manner. It's an alternative to the XML-based configuration.

Also, if you want to migrate your project from XML to Java config, please refer to this article.

Q14. Can We Have Multiple Spring Configuration Files in One Project?

Yes, in large projects, having multiple Spring configurations is recommended to increase maintainability and modularity.

You can load multiple Java-based configuration files:

@Configuration @Import({MainConfig.class, SchedulerConfig.class}) public class AppConfig {

Or load one XML file that will contain all other configs:

ApplicationContext context = new ClassPathXmlApplicationContext("spring-all.xml");

And inside this XML file you'll have:

Q15. What Is Spring Security?

Spring Security is a separate module of the Spring framework that focuses on providing authentication and authorization methods in Java applications. It also takes care of most of the common security vulnerabilities such as CSRF attacks.

To use Spring Security in web applications, you can get started with a simple annotation: @EnableWebSecurity.

You can find the whole series of articles related to security on Baeldung.

Q16. What Is Spring Boot?

Spring Boot is a project that provides a pre-configured set of frameworks to reduce boilerplate configuration so that you can have a Spring application up and running with the smallest amount of code.

Q17. Name Some of the Design Patterns Used in the Spring Framework?

  • Singleton Pattern: Singleton-scoped beans
  • Factory Pattern: Bean Factory classes
  • Prototype Pattern: Prototype-scoped beans
  • Adapter Pattern: Spring Web and Spring MVC
  • Proxy Pattern: Spring Aspect Oriented Programming support
  • Template Method Pattern:JdbcTemplate, HibernateTemplate, etc.
  • Front Controller: Spring MVC DispatcherServlet
  • Data Access Object: Spring DAO support
  • Model View Controller: Spring MVC

Q18. How Does the Scope Prototype Work?

Scope prototype means that every time you call for an instance of the Bean, Spring will create a new instance and return it. This differs from the default singleton scope, where a single object instance is instantiated once per Spring IoC container.

3. Spring Web MVC

Q19. How to Get ServletContext and ServletConfig Objects in a Spring Bean?

You can do either by:

  1. Implementing Spring-aware interfaces. The complete list is available here.
  2. Using @Autowired annotation on those beans:
@Autowired ServletContext servletContext; @Autowired ServletConfig servletConfig;

Q20. What Is a Controller in Spring Mvc?

Simply put, all the requests processed by the DispatcherServlet are directed to classes annotated with @Controller. Each controller class maps one or more requests to methods that process and execute the requests with provided inputs.

If you need to take a step back, we recommend having a look at the concept of the Front Controller in the typical Spring MVC architecture.

Q21. How Does the @Requestmapping Annotation Work?

The @RequestMapping annotation is used to map web requests to Spring Controller methods. In addition to simple use cases, we can use it for mapping of HTTP headers, binding parts of the URI with @PathVariable, and working with URI parameters and the @RequestParam annotation.

More details on @RequestMapping are available here.

For more Spring MVC questions, please check out Spring MVC Interview Questions article.

4. Spring Data Access

Q22. What Is Spring Jdbctemplate Class and How to Use It?

The Spring JDBC template is the primary API through which we can access database operations logic that we’re interested in:

  • creation and closing of connections
  • executing statements and stored procedure calls
  • iterating over the ResultSet and returning results

To use it, we'll need to define the simple configuration of DataSource:

@Configuration @ComponentScan("org.baeldung.jdbc") public class SpringJdbcConfig { @Bean public DataSource mysqlDataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/springjdbc"); dataSource.setUsername("guest_user"); dataSource.setPassword("guest_password"); return dataSource; } }

For further explanation, you can go through this quick article.

Q23. How Would You Enable Transactions in Spring and What Are Their Benefits?

There are two distinct ways to configure Transactions – with annotations or by using Aspect Oriented Programming (AOP) – each with their advantages.

The benefits of using Spring Transactions, according to the official docs, are:

  • Provide a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO
  • Support declarative transaction management
  • Provide a simpler API for programmatic transaction management than some complex transaction APIs such as JTA
  • Integrate very well with Spring's various data access abstractions

Q24. What Is Spring Dao?

Spring Data Access Object is Spring's support provided to work with data access technologies like JDBC, Hibernate, and JPA in a consistent and easy way.

You can, of course, go more in-depth on persistence, with the entire series discussing persistence in Spring.

5. Spring Aspect-Oriented Programming (AOP)

Q25. What Is Aspect-Oriented Programming?

Aspects enable the modularization of cross-cutting concerns such as transaction management that span multiple types and objects by adding extra behavior to already existing code without modifying affected classes.

Here is the example of aspect-based execution time logging.

Q26. What Are Aspect, Advice, Pointcut, and Joinpoint in Aop?

  • Aspect: a class that implements cross-cutting concerns, such as transaction management
  • Advice: the methods that get executed when a specific JoinPoint with matching Pointcut is reached in the application
  • Pointcut: a set of regular expressions that are matched with JoinPoint to determine whether Advice needs to be executed or not
  • JoinPoint: a point during the execution of a program, such as the execution of a method or the handling of an exception

Q27. What Is Weaving?

According to the official docs, weaving is a process that links aspects with other application types or objects to create an advised object. This can be done at compile time, load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.

6. Spring 5

Q28. What Is Reactive Programming?

Reactive programming is about non-blocking, event-driven applications that scale with a small number of threads, with back pressure being a key ingredient that aims to ensure producers don't overwhelm consumers.

The primary benefits of reactive programming are:

  • increased utilization of computing resources on multicore and multi-CPU hardware
  • and increased performance by reducing serialization

Reactive programming is generally event-driven, in contrast to reactive systems, which are message-driven. Thus, using reactive programming does not mean we're building a reactive system, which is an architectural style.

However, reactive programming may be used as a means to implement reactive systems if we follow the Reactive Manifesto, which is quite vital to understand.

Based on this, reactive systems have four important characteristics:

  • Responsive: the system should respond in a timely manner
  • Resilient: in case the system faces any failure, it should stay responsive
  • Elastic: reactive systems can react to changes and stay responsive under varying workload
  • Message-driven: reactive systems need to establish a boundary between components by relying on asynchronous message passing

Q29. What Is Spring Webflux?

Spring WebFlux is Spring's reactive-stack web framework, and it's an alternative to Spring MVC.

In order to achieve this reactive model and be highly scalable, the entire stack is non-blocking. Check out our tutorial on Spring 5 WebFlux for additional details.

Q30. What Are the Mono and Flux Types?

The WebFlux framework in Spring Framework 5 uses Reactor as its async foundation.

This project provides two core types: Mono to represent a single async value, and Flux to represent a stream of async values. They both implement the Publisher interface defined in the Reactive Streams specification.

Mono implements Publisher and returns 0 or 1 elements:

public abstract class Mono implements Publisher {...}

Also, Flux implements Publisher and returns N elements:

public abstract class Flux implements Publisher {...}

By definition, the two types represent streams, hence they're both lazy, which means nothing is executed until we consume the stream using the subscribe() method. Both types are immutable, therefore calling any method will return a new instance of Flux or Mono.

Q31. What Is the Use of Webclient and Webtestclient?

WebClient is a component in the new Web Reactive framework that can act as a reactive client for performing non-blocking HTTP requests. Being a reactive client, it can handle reactive streams with back pressure, and it can take full advantage of Java 8 lambdas. It can also handle both sync and async scenarios.

On the other hand, the WebTestClient is a similar class that we can use in tests. Basically, it's a thin shell around the WebClient. It can connect to any server over an HTTP connection. It can also bind directly to WebFlux applications using mock request and response objects, without the need for an HTTP server.

Q32. What Are the Disadvantages of Using Reactive Streams?

The major disadvantages of using reactive streams are:

  • Troubleshooting a Reactive application is a bit difficult; be sure to check out our tutorial on debugging reactive streams for some handy debugging tips
  • There is limited support for reactive data stores, as traditional relational data stores have yet to embrace the reactive paradigm
  • There's an extra learning curve when implementing

Q33. Is Spring 5 Compatible With Older Versions of Java?

In order to take advantage of Java 8 features, the Spring codebase has been revamped. This means older versions of Java cannot be used. Hence, the framework requires a minimum of Java 8.

Q34. How Does Spring 5 Integrate With Jdk 9 Modularity?

In Spring 5, everything has been modularized, thus we won't be forced to import jars that may not have the functionalities we're looking for.

Please have a look at our guide to Java 9 modularity for an in-depth understanding of how this technology works.

Let's see an example to understand the new module functionality in Java 9 and how to organize a Spring 5 project based on this concept.

To start, let's create a new class that contains a single method to return a String “HelloWorld”. We'll place this within a new Java project – HelloWorldModule:

package com.hello; public class HelloWorld { public String sayHello(){ return "HelloWorld"; } }

Then let's create a new module:

module com.hello { export com.hello; }

Now, let's create a new Java Project, HelloWorldClient, to consume the above module by defining a module:

module com.hello.client { requires com.hello; }

The above module will be available for testing now:

public class HelloWorldClient { public static void main(String[] args){ HelloWorld helloWorld = new HelloWorld(); log.info(helloWorld.sayHello()); } }

Q35. Can We Use Both Web Mvc and Webflux in the Same Application?

As of now, Spring Boot will only allow either Spring MVC or Spring WebFlux, as Spring Boot tries to auto-configure the context depending on the dependencies that exist in its classpath.

또한 Spring MVC는 Netty에서 실행할 수 없습니다. 또한 MVC는 차단 패러다임이고 WebFlux는 비 차단 스타일이므로 서로 다른 목적을 제공하므로 두 가지를 함께 혼합해서는 안됩니다.

7. 결론

이 광범위한 기사에서 우리는 Spring에 대한 모든 기술 인터뷰에서 가장 중요한 몇 가지 질문을 탐색했습니다.

이 기사가 다가오는 봄 인터뷰에서 도움이되기를 바랍니다. 행운을 빕니다!

« 이전 Java 주석 인터뷰 질문 (+ 답변)