Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why use Spring as the Java framework

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "Why to use Spring as a Java framework", the content of the explanation is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Why to use Spring as a Java framework" bar!

1. Overview

In this article, we will discuss the main value embodiment of Spring as one of the most popular Java frameworks.

Most importantly, we will try to understand why Spring is our framework of choice. The details of Spring and its components have been widely covered in our previous tutorials. Therefore, we will skip the introductory "how to" section and focus on "why".

two。 Why use any framework?

Before we start any discussion about Spring, let's first understand why we need to use any framework in the first place.

General-purpose programming languages like Java can support a variety of applications. Not to mention Java is actively improving every day.

In addition, numerous open source and proprietary libraries support Java in this regard.

So why on earth do we need a framework? To be honest, it is not absolutely necessary to use a framework to accomplish a task. However, it is usually wise to use one for the following reasons:

Help us focus on the core task, not on the templates associated with it

Has gathered years of wisdom in the form of design patterns.

Help us comply with industry and regulatory standards

Reduce the total cost of ownership of the application

We have just touched the surface, and we must say that the benefits are hard to ignore. But this can't be positive, so it's important to note:

Force us to write applications in a specific way

Bind to specific versions of languages and libraries

Resource usage added to the application

Frankly, there is no silver bullet in software development and frameworks, and Java is no exception. Therefore, you should choose which framework or not to use according to the context.

At the end of this article, we will make better decisions about Spring in Java.

3. A brief overview of the Spring ecosystem

Before we begin a qualitative assessment of the Spring framework, let's take a closer look at what the Spring ecosystem looks like.

Spring appeared sometime in 2003, when Java Enterprise Edition was growing rapidly, and developing enterprise applications was exciting, but also boring!

Spring was originally an IoC container for Java. We still mainly associate Spring with it, and in fact, it forms the core of the framework, as well as other projects developed on that basis.

3.1. Spring framework

The Spring framework is divided into multiple modules, which makes it easy to choose which parts to use in any application:

Core: provides core features such as DI (dependency injection), internationalization, validation, and AOP (aspect-oriented programming)

Data Access: supports data access through JTA (Java transaction API), JPA (Java persistence API), and JDBC (Java database connection)

Web: supports both Servlet API (Spring MVC) and the most recent reactive API (Spring WebFlux), as well as WebSockets, STOMP and WebClient

Integration: supports integration into enterprise Java through JMS (Java message Service), JMX (Java Management extension), and RMI (remote method invocation)

Testing: support units and integration tests through mock objects, test fixtures, context management, and caching

3.2. Spring project

But what is more valuable for Spring is a strong ecosystem that has been developing and growing over the years. Their structures are Spring projects, and they are developed on top of the Spring framework.

Although the list of Spring projects is long and constantly changing, there are a few things worth mentioning:

Boot: provides us with a set of highly customized but extensible templates for creating various Spring-based projects with little time. It makes it very easy to create stand-alone Spring applications using embedded Tomcat or similar containers.

Cloud: provides support for easily developing common distributed system patterns, such as service discovery, circuit breakers, and API gateways. It helps us reduce the workload of deploying such boilerplate patterns on local, remote, and even hosted platforms.

Security: provides a robust mechanism for developing authentication and authorization for Spring-based projects in a highly customizable manner. With minimal declarative support, we can gain protection against common attacks, such as session fixing, click hijacking, and cross-site request forgery.

Mobile: provides the ability to detect devices and adjust application behavior accordingly. In addition, device-aware view management is supported for the best user experience, site preference management, and site switchers.

Batch: provides a lightweight framework for developing batch applications for enterprise systems such as data archiving. Intuitive support for scheduling, restarting, skipping, collecting metrics and logging. In addition, it supports the expansion of high-volume jobs through optimization and partitioning.

There is no doubt that this is a fairly abstract introduction to what Spring provides. But it provides us with a sufficient basis for further discussion about the organization and breadth of Spring.

4. Spring operation

People are used to adding a hello world program to learn about any new technology.

Let's take a look at how Spring makes it easy to write a program that isn't just Hello World. We will create an application that exposes the CRUD operation as the REST API of a domain entity, such as an employee supported by an in-memory database. More importantly, we will use basic authentication to protect our mutation endpoints. Finally, no application can really be completed without good, old unit tests.

4.1. Project setup

We will use Spring Initializr to set up the Spring Boot project, which is a convenient online tool to guide projects with correct dependencies. We will add Web, JPA, H2, and Security as project dependencies to get the Maven configuration settings correctly. More details are guided in one of our previous articles.

4.2. Domain model and persistence

Since little needs to be done, we are ready to define the domain model and persistence.

Let's first define Employee as a simple JPA entity:

Entitypublic class Employee {@ Id @ GeneratedValue (strategy = GenerationType.AUTO) private Long id; @ NotNull private String firstName; @ NotNull private String lastName; / / Standard constructor, getters and setters}

Notice that we include the automatically generated id in the entity definition.

Now we must define the JPA repository for the entity. This is where Spring makes it very simple:

Public interface EmployeeRepository extends CrudRepository {List findAll ();}

All we have to do is define such an interface, and Spring JPA will provide us with an implementation fleshed out with default and custom actions. It's pretty neat! You can find more details about using Spring Data JPA in our other articles.

4.3. Controller

Now we must define a network controller to route and process our incoming requests:

RestControllerpublic class EmployeeController {@ Autowired private EmployeeRepository repository; @ GetMapping ("/ employees") public List getEmployees () {return repository.findAll ();} / / Other CRUD endpoints handlers}

In fact, all we have to do is annotate the class and define the routing meta-information and each handler method.

In our previous article, we discussed in detail how to use the Spring REST controller.

4.4. Safety

So now that we've defined everything, how do we protect things like creating or deleting employees? We don't want unauthenticated access to these endpoints!

Spring Security is very good at this:

@ EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@ Override protected void configure (HttpSecurity http) throws Exception {http .authorizeRequests () .antM atchers (HttpMethod.GET, "/ employees", "/ employees/**") .permitAll () .anyRequest () .authenticated () .and () .httpBasic ();} / / other necessary beans and definitions}

There are more details to understand here, but the most important point is that we only allow GET to operate in an unrestricted declarative manner.

4.5. test

Now we've done everything, but wait, how do we test this?

Let's see if Spring makes it easier to write unit tests for REST controllers:

@ RunWith (SpringRunner.class) @ SpringBootTest (webEnvironment = WebEnvironment.RANDOM_PORT) @ AutoConfigureMockMvcpublic class EmployeeControllerTests {@ Autowired private MockMvc mvc @ Test @ WithMockUser () public void givenNoEmployee_whenCreateEmployee_thenEmployeeCreated () throws Exception {mvc.perform (post ("/ employees") .content (new ObjectMapper () .writeValueAsString (new Employee ("First") "Last") .with (csrf ()) .contentType (MediaType.APPLICATION_JSON) .accept (MediaType.APPLICATION_JSON) .andexpect (MockMvcResultMatchers.status () .isCreated ()) .andexpect (jsonPath ("$.firstName", is ("First")) .andexpect (jsonPath ("$.lastName", is ("Last") } / / other tests as necessary}

As we have seen, Spring provides us with the necessary infrastructure to write simple unit and integration tests that would otherwise depend on the Spring context to initialize and configure.

4.6. Run the application

Finally, how do we run this application? This is another interesting aspect of Spring Boot. Although we can package it as a regular application and traditionally deploy it on a Servlet container.

But there's nothing funny about it! Spring Boot comes with an embedded Tomcat server:

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

This is a pre-created class that, as part of the bootstrapper, has all the necessary details to start this application using an embedded server.

In addition, it is highly customizable.

5. Substitutes for Spring

Although it is relatively easy to choose to use frameworks, choosing between frames usually makes our choices difficult. To do this, however, we must at least get a rough idea of the alternatives to the functionality provided by Spring.

As mentioned earlier, the Spring framework and its projects provide a wide range of choices for enterprise developers. If we do a quick assessment of contemporary Java frameworks, they can't even be compared to the ecosystems that Spring provides to us.

However, for specific areas, they do form a compelling argument for choosing alternatives:

Guice: provides a robust IoC container for Java applications

Play: very suitable for Web framework with responsive support

Hibernate: a data access Framework based on JPA support

In addition to these, there are some new features that provide broader support than specific areas, but still do not cover everything that Spring must provide:

Micronaut: a JVM-based framework customized for cloud-based local micro services

Quarkus: a new era of Java stack that promises faster startup time and smaller memory footprint

Obviously, it is neither necessary nor feasible to fully iterate through this list, but we have a broad concept here.

6. Why choose Spring?

Finally, we built all the necessary contexts to solve our core problem. Why Spring? We understand how frameworks can help us develop complex enterprise applications.

In addition, we understand the choices we make for specific issues, such as Web, data access, framework integration, and especially Java.

Now, of all this, what's the highlight of Spring? Let's explore.

6.1. Usability

A key aspect of the popularity of any framework is how easy it is for developers to use it. Spring makes it easy for developers to launch and then configure exactly what they need through a number of configuration options and conventions over configuration.

Projects like Spring Boot make it easy to boot a complex Spring project. Not to mention, it has excellent documentation and tutorials to help anyone get started.

6.2. Modularization

Another key aspect of Spring's popularity is its highly modular nature. We can choose to use the entire Spring framework or only the necessary modules. In addition, we can choose to include one or more Spring projects as needed.

Also, we can choose to use other frameworks such as Hibernate or Struts!

6.3. Consistency

Although Spring does not support all Java EE specifications, it supports all technologies and usually increases support for standard specifications when necessary. For example, Spring supports JPA-based repositories, so switching providers become trivial.

In addition, Spring supports industry specifications such as Reactive Stream under Spring Web Reactive and HATEOAS under Spring HATEOAS.

6.4. Testability

Adopting any framework also depends to a large extent on how easy it is to test the applications built on it. The core of Spring is to advocate and support test-driven development (TDD).

Spring applications are mainly made up of POJO, which naturally makes unit testing much easier. However, Spring does provide Mock objects for scenarios such as MVC, otherwise unit testing becomes complex.

6.5. mature

Spring has a long history of innovation, adoption and standardization. Over the years, it has matured enough to become the default solution to the most common problems in large enterprise application development.

What is even more exciting is active development and maintenance. Support for new language features and enterprise integration solutions is being developed every day.

6.6. Community support

Last but not least, any framework or even class library survives in the industry through innovation, and there is no better place for innovation than the community. Spring is open source software led by Pivotal Software and supported by large organizations and individual developers.

This means that it still has background significance and is often futuristic, as can be seen in the number of projects it owns.

7. Reasons for not using Spring

There are a variety of applications that can benefit from different levels of Spring usage, and such applications are changing as fast as Spring.

However, we must understand that Spring, like other frameworks, helps manage the complexity of application development. It helps us avoid common pitfalls and keeps applications maintainable over time.

This is at the cost of an additional resource footprint and learning curve, although it may be small. If there is an application that is simple enough and is not expected to become complex, it may be more beneficial not to use any framework at all!

8. Conclusion

In this article, we discussed the benefits of using frameworks in application development. We also discussed the Spring framework briefly.

In discussing this topic, we also looked at some alternative frameworks that can be used for Java.

Finally, we discussed the reasons that prompted us to choose Spring as the Java selection framework.

However, we should give some suggestions at the end of this article. Although it sounds persuasive, there is usually no single, general solution in software development.

Therefore, we must use our wisdom to choose the simplest solution for the specific problems we want to solve.

Thank you for your reading, the above is the content of "Why to use Spring as the Java framework". After the study of this article, I believe you have a deeper understanding of why you use Spring as the Java framework, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report