Сравнение между пролетта и пролетта

1. Общ преглед

В това описание ще разгледаме разликите между стандартните Spring Spring и Spring Boot.

Ще се съсредоточим върху и ще обсъдим как модулите на Spring, като MVC и Security, се различават, когато се използват в основната Spring в сравнение, когато се използват с Boot.

2. Какво е пролетта?

Най-просто казано, Spring рамката предоставя цялостна инфраструктурна поддръжка за разработване на Java приложения .

Той е пълен с някои приятни функции като Dependency Injection и готови модули като:

  • Пролетен JDBC
  • Пролетен MVC
  • Пролетна сигурност
  • Пролетен AOP
  • Пролетен ORM
  • Пролетен тест

Тези модули могат драстично да намалят времето за разработка на приложение.

Например в ранните дни на уеб разработката на Java трябваше да напишем много шаблонни кодове, за да вмъкнем запис в източник на данни. Но използвайки JDBCTemplate на модула Spring JDBC, можем да го намалим до няколко реда код само с няколко конфигурации.

3. Какво представлява Spring Boot?

Spring Boot е основно разширение на Spring структурата, което елиминира конфигурациите на бойлер, необходими за настройка на приложение Spring.

Той взема мнителен поглед върху пролетната платформа, която проправи пътя за по-бързо и по-ефективно развитие на екосистемата .

Ето само някои от функциите в Spring Boot:

  • Предпочитани „стартерни“ зависимости за опростяване на изграждането и конфигурирането на приложението
  • Вграден сървър, за да се избегне сложността при разполагане на приложения
  • Показатели, проверка на състоянието и външна конфигурация
  • Автоматично конфигуриране за пролетната функционалност - когато е възможно

Нека се запознаем стъпка по стъпка с двете рамки.

4. Зависимости на Maven

Първо, нека разгледаме минималните зависимости, необходими за създаване на уеб приложение с помощта на Spring:

 org.springframework spring-web 5.2.9.RELEASE   org.springframework spring-webmvc 5.2.9.RELEASE 

За разлика от Spring, Spring Boot изисква само една зависимост, за да стартира и работи уеб приложение:

 org.springframework.boot spring-boot-starter-web 2.3.4.RELEASE 

Всички други зависимости се добавят автоматично към окончателния архив по време на изграждането.

Друг добър пример е тестване на библиотеки. Обикновено използваме набора от библиотеки Spring Test, JUnit, Hamcrest и Mockito. В пролетен проект трябва да добавим всички тези библиотеки като зависимости.

Но в Spring Boot се нуждаем само от стартерната зависимост за тестване, за да включим автоматично тези библиотеки.

Spring Boot осигурява редица стартерни зависимости за различни Spring модули. Някои от най-често използваните са:

  • spring-boot-starter-data-jpa
  • spring-boot-starter-security
  • пролетен тест за стартиране
  • spring-boot-starter-web
  • пружинен ботуш-стартер-мащерка

За пълния списък с начинаещи вижте и пролетната документация.

5. MVC конфигурация

Нека разгледаме конфигурацията, необходима за създаване на JSP уеб приложение, използвайки Spring и Spring Boot.

Spring изисква дефиниране на сървлета на диспечера, съпоставянията и други поддържащи конфигурации. Можем да направим това, като използваме файла web.xml или клас Initializer :

public class MyWebAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext container) { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.setConfigLocation("com.baeldung"); container.addListener(new ContextLoaderListener(context)); ServletRegistration.Dynamic dispatcher = container .addServlet("dispatcher", new DispatcherServlet(context)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } }

Ние също трябва да добавите @EnableWebMvc анотацията към @Configuration клас и да определят цел-за преобразуване за решаване на вижданията върнати от контролери:

@EnableWebMvc @Configuration public class ClientWebConfig implements WebMvcConfigurer { @Bean public ViewResolver viewResolver() { InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); return bean; } }

В сравнение с всичко това, Spring Boot се нуждае само от няколко свойства, за да накара нещата да работят, след като добавим уеб стартера:

spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp

Цялата конфигурация на Spring по-горе се включва автоматично чрез добавяне на уеб стартера за стартиране чрез процес, наречен автоматична конфигурация.

Това означава, че Spring Boot ще разгледа зависимостите, свойствата и компонентите, които съществуват в приложението, и ще даде възможност за конфигуриране въз основа на тях.

Разбира се, ако искаме да добавим собствена персонализирана конфигурация, тогава автоматичното конфигуриране на Spring Boot ще отстъпи.

5.1. Конфигуриране на Template Engine

Нека сега научим как да конфигурираме механизъм за шаблони на Thymeleaf както в Spring, така и в Spring Boot.

През пролетта трябва да добавим зависимостта thymeleaf-spring5 и някои конфигурации за преобразувателя на изглед:

@Configuration @EnableWebMvc public class MvcWebConfig implements WebMvcConfigurer { @Autowired private ApplicationContext applicationContext; @Bean public SpringResourceTemplateResolver templateResolver() { SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(applicationContext); templateResolver.setPrefix("/WEB-INF/views/"); templateResolver.setSuffix(".html"); return templateResolver; } @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); templateEngine.setEnableSpringELCompiler(true); return templateEngine; } @Override public void configureViewResolvers(ViewResolverRegistry registry) { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine()); registry.viewResolver(resolver); } }

Пролет Boot 1 изисква само зависимостта на пролетно-обувка стартер thymeleaf да се даде възможност Thymeleaf подкрепа в уеб приложение. Но поради новите функции в Thymeleaf3.0, ние трябва да добавим thymeleaf-layout-dialect също като зависимост в уеб приложението Spring Boot 2. Като алтернатива можем да изберем да добавим зависимост от пружинен старт-стартер-мащерка, която ще се погрижи за всичко това вместо нас.

Once the dependencies are in place, we can add the templates to the src/main/resources/templates folder and the Spring Boot will display them automatically.

6. Spring Security Configuration

For the sake of simplicity, we'll see how the default HTTP Basic authentication is enabled using these frameworks.

Let's start by looking at the dependencies and configuration we need to enable Security using Spring.

Spring requires both the standard spring-security-web and spring-security-config dependencies to set up Security in an application.

Next, we need to add a class that extends the WebSecurityConfigurerAdapter and makes use of the @EnableWebSecurity annotation:

@Configuration @EnableWebSecurity public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user1") .password(passwordEncoder() .encode("user1Pass")) .authorities("ROLE_USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }

Here we're using inMemoryAuthentication to set up the authentication.

Similarly, Spring Boot also requires these dependencies to make it work. But we need to define only the dependency ofspring-boot-starter-security as this will automatically add all the relevant dependencies to the classpath.

The security configuration in Spring Boot is the same as the one above.

If you need to know how the JPA configuration can be achieved in both Spring and Spring Boot, then check out our article A Guide to JPA with Spring.

7. Application Bootstrap

The basic difference in bootstrapping of an application in Spring and Spring Boot lies with the servlet. Spring uses either the web.xml or SpringServletContainerInitializer as its bootstrap entry point.

On the other hand, Spring Boot uses only Servlet 3 features to bootstrap an application. Let's talk about this in detail.

7.1. How Spring Bootstraps?

Spring supports both the legacy web.xml way of bootstrapping as well as the latest Servlet 3+ method.

Let's see the web.xml approach in steps:

  1. Servlet container (the server) reads web.xml
  2. The DispatcherServlet defined in the web.xml is instantiated by the container
  3. DispatcherServlet creates WebApplicationContext by reading WEB-INF/{servletName}-servlet.xml
  4. Finally, the DispatcherServlet registers the beans defined in the application context

Here's how Spring bootstraps using Servlet 3+ approach:

  1. The container searches for classes implementing ServletContainerInitializer and executes
  2. The SpringServletContainerInitializer finds all classes implementing WebApplicationInitializer
  3. The WebApplicationInitializer creates the context with XML or @Configuration classes
  4. The WebApplicationInitializer creates the DispatcherServlet with the previously created context.

7.2. How Spring Boot Bootstraps?

The entry point of a Spring Boot application is the class which is annotated with @SpringBootApplication:

@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

By default, Spring Boot uses an embedded container to run the application. In this case, Spring Boot uses the public static void main entry-point to launch an embedded web server.

Also, it takes care of the binding of the Servlet, Filter, and ServletContextInitializer beans from the application context to the embedded servlet container.

Another feature of Spring Boot is that it automatically scans all the classes in the same package or sub packages of the Main-class for components.

Spring Boot provides the option of deploying it as a web archive in an external container as well. In this case, we have to extend the SpringBootServletInitializer:

@SpringBootApplication public class Application extends SpringBootServletInitializer { // ... }

Here the external servlet container looks for the Main-class defined in the META-INF file of the web archive and the SpringBootServletInitializer will take care of binding the Servlet, Filter, and ServletContextInitializer.

8. Packaging and Deployment

Finally, let's see how an application can be packaged and deployed. Both of these frameworks support the common package managing technologies like Maven and Gradle. But when it comes to deployment, these frameworks differ a lot.

For instance, the Spring Boot Maven Plugin provides Spring Boot support in Maven. It also allows packaging executable jar or war archives and running an application “in-place”.

Some of the advantages of Spring Boot over Spring in the context of deployment include:

  • Provides embedded container support
  • Provision to run the jars independently using the command java -jar
  • Option to exclude dependencies to avoid potential jar conflicts when deploying in an external container
  • Option to specify active profiles when deploying
  • Random port generation for integration tests

9. Conclusion

В този урок научихме за разликите между Spring и Spring Boot.

С няколко думи можем да кажем, че Spring Boot е просто продължение на самата Spring, за да направи разработката, тестването и внедряването по-удобни.