Why did you choose Java as the Spring Framework

1 Overview

In this article, we will discuss the Spring as the main value of the most popular Java framework embodied.

Most importantly, we will try to understand why we choose to become Spring Framework.

2. Why use any framework?

Before we start any discussion of Spring, first let us understand why we need to use any framework.

Such as general-purpose programming language Java to support multiple applications. Not to mention Java are actively improving every day.

In addition, there are numerous open source and proprietary Java library support in this regard.

So, exactly why we need a framework for it? Honestly, use frames to complete the task is not absolutely necessary. However, for several reasons, usually using a sensible:

  • Help us to focus on our core mission, rather than a model with relevant
  • It brings together many years of wisdom in the form of design patterns
  • Help us comply with industry and regulatory standards
  • Reduce total cost of ownership application

We have just scratched the surface, we must say that the benefits of hard to ignore. But that can not be positive, it should be noted that:

  • It forces us to write applications in a particular way
  • Bound to a specific version of the language and libraries
  • Added to the application's resource consumption

Frankly, there is no silver bullet in software development and frameworks, Java is no exception. Therefore, you should select which frame the context or without frame.

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

3. Spring brief overview of the ecosystem

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

Spring is appearing sometime in 2003 , when the rapid development of Java Enterprise Edition, enterprise application development is very exciting, but also very boring!

Spring was originally a Java- a Inversion of Control (IoC) container . We still primarily Spring contact it up, in fact, it constitutes the core framework, as well as other projects developed on this basis.

3.1. Spring Framework

Spring Framework is divided into a plurality of modules , which makes it can be easily selected to be used in any part of the application:

  • Core : provides core features, such as DI (dependency injection), internationalization, and the AOP validation (Aspect Oriented Programming)
  • Access the Data : Support by JTA (Java Transaction API), JPA (Java Persistence API) and JDBC (Java Database Connectivity) to access data
  • Web : API supports Servlet ( the Spring MVC ) and reactive recent API ( the Spring WebFlux ), and also supports WebSockets, STOMP and WebClient
  • Integration : Support by JMS (Java Message Service), JMX (Java Management Extensions) and RMI (Remote Method Invocation) integration into enterprise Java
  • Testing : simulated target, the test device, context management support unit and integration test

3.2. Spring project

However, Spring more valuable is a strong ecosystem, the ecosystem has been in development for many years, and is still evolving. Their structure is Spring project , which was developed over the Spring framework.

Despite the long list of Spring project, and has been changing, but there are some places worth mentioning:

  • The Boot : provides a highly customizable set of templates but can be extended for us, for creating Spring-based projects in the case of hardly takes time. It makes use of an embedded Tomcat or similar container to create a separate Spring applications very easily.
  • Cloud : providing support to easily develop some common patterns of distributed systems, such as service discovery, circuit breakers, and the API gateway. It helps us to reduce the workload of the deployment of such a model in the mode of local, remote and even hosting platform.
  • Security : provide a mechanism robust, highly customizable way for authentication and authorization identities based on Spring project development. With minimal declarative support, we can get protection against common attacks such as session fixation, clickjacking and cross-site request forgery.
  • Mobile : providing a detection device and adjustment application behavior accordingly. In addition, the perception of support for View Manager device to get the best user experience, site preferences and site management switch.
  • BATCH : providing a lightweight framework for data archiving system development enterprise batch processing applications. Scheduling, reboot, skip, collect metrics and intuitive logging support. In addition, also supports expansion of the capacity of the job by optimizing and partitions.

Needless to say, this is Spring content provided a rather abstract presentation. But it provides a sufficient basis on Spring and breadth of the organization for us, so that we can discuss further.

4. Spring Operation

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

Let's see how Spring lets just write a Hello World program has become easier . We will create an application, the application will CRUD operations as a public domain entity (such as a memory database support employees) of the REST API. More importantly, we will use basic authentication to protect our mutation endpoint. Finally, there is no good, the old unit testing, any application can not be truly complete.

4.1. Project Settings

We will use Spring Initializr set Spring Boot project, this is a convenient online tool that can guide the correct dependencies of the project. We will add the Web, JPA, H2 and Security as a project dependencies to correctly obtain Maven configuration settings. More details of the guide in one of our previous articles.

4.2 domain model and persistence

Because almost do not need to do anything, we are ready to define the domain model and persistence.

Let's first Employee is defined as a simple JPA entities:

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

 

 

Note that we have included in automatically generated id entity definition.

Now we have to define the JPA entity repository. This is the Spring make it very simple place:

public interface EmployeeRepository 
  extends CrudRepository<Employee, Long> {
    List<Employee> findAll();
}

 

 

We have to do is define an interface like this, the Spring JPA will provide us with a full realization of the default and custom actions . Pretty neat! In our other articles you can find more information about using Spring Data JPA details.

4.3 Controller

Now we have to define a network controller routing and processing of our incoming requests:

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

 

 

In fact, we have to do is use this annotation to define the class meta-information and routing and handling procedures for each method.

We discussed in detail in our previous article how to use the Spring REST controller .

4.4. Security

So now we have defined all the content, but how to create or delete operations to protect employees like it? We do not want access to these endpoints unauthenticated!

Spring Security is very good in this regard:

@EnableWebSecurity
public class WebSecurityConfig 
  extends WebSecurityConfigurerAdapter {

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

 

 

Here are more details need to pay attention to understand , but the most important point is that we allow only declarative way GET operation is not restricted.

4.5. Test

Now that we have done everything, but wait, how do we do this test?

Let's see if we can make the preparation of Spring REST controller unit testing easier:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public 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 testing , otherwise these tests will depend on the Spring context to be initialized and configured.

4.6. Run the application

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

But what fun! Spring Boot comes with an embedded Tomcat server :

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

 

 

This class is a pre-created as part of the boot program, with all the necessary details using the embedded server to start this application.

In addition, it is highly customizable .

5. Spring alternatives

Although the choice of using a framework is relatively easy, but usually let to choose between the frames our choice becomes difficult. But this, we must at least roughly understand what features are provided by Spring alternatives.

As mentioned earlier, the Spring Framework and its projects provide a wide range of options for enterprise developers . If we do a quick assessment of the contemporary Java framework, they can not even provide us with the Spring ecosystem par.

However, for a specific field, they do form a compelling argument to select alternatives:

  • Guice : IoC container to provide a robust Java applications
  • Play : very suitable as a Web framework responsive support
  • Hibernate : a JPA-based data access framework to support the

In addition to these, there are some new features provide more extensive than specific areas of support, but still not cover everything Spring has to offer:

  • Micronaut : a framework based on the JVM for cloud services tailored to local micro
  • Quarkus : a new era of Java stack, it promises to provide faster boot times and smaller memory footprint

Obviously, this list is completely iterative neither necessary nor feasible, but we are here to get a broad concept.

6. Why Spring?

Finally, we build all the necessary context to address our core problem, why is Spring? We understand framework can help us to develop complex enterprise applications approach.

In addition, we understand that we have chosen for a particular issue have done, such as integrated Web, data access framework, especially in Java.

Now, among all these, Spring's highlights where? Let's explore.

6.1. Usability

A key aspect of any framework for developers to use popular is how easy it is yes. Spring through multiple configuration options and convention over configuration makes it easy for developers to start, then configure exactly what they need .

Like Spring Boot such a complex project such that the guide Spring project becomes very simple . Needless to say, it has excellent documentation and tutorials to help anyone get started.

6.2. Modular

Another key aspect of the Spring popular is its highly modular characteristics. We can choose to use the entire Spring framework or use only the necessary modules. In addition, we may need to select contains one or more items Spring.

Moreover, we can also choose to use other frameworks such as Hibernate and Struts!

6.3. Consistency

Although Spring does not support all the Java EE specification, but it supports all technologies , generally improve support for standards when necessary. For example, Spring supports JPA repository, thus providing the switching process becomes negligible.

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

6.4. Testability

How easy it is to use any framework to a large extent also depends on the application test on which to build. Spring is the core advocacy and support for test-driven development (TDD).

Spring application POJO mainly composed of the cell which naturally relatively much simpler test. However, Spring does provide for the MVC Mock objects and other scene, otherwise the unit testing becomes complicated.

6.5. Mature

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

Even more exciting is the positive development and maintenance. Every day in developing support for new language features and enterprise integration solutions.

6.6. Community support

Last but not least, any framework class libraries are even survive through innovation in the industry, and there is no better place than the innovation community. Spring is the leading open-source software Pivotal Software, backed by large organizations and individual developers composed.

This means that it still has a background sense, and often has a futuristic, it's that the number of items can clearly be seen.

7. reasons for not using Spring

There are a wide variety of applications can benefit from the use of different levels in the Spring, and this change applications with Spring growing as fast.

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

This is to footprint and additional resources at the expense of the learning curve , although it may be small. If indeed there is a simple enough and is not expected to complicate the application, does not use any framework could bring more benefits!

8. Conclusion

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

In discussing this topic, we also investigated some alternative framework for Java.

Finally, we discussed the reasons why we have chosen as the Spring Java framework of choice.

However, we should give some suggestions at the end of this article. Although it sounds very convincing, but in software development is usually no single, universal solution .

Therefore, we must use our wisdom, choose the simplest solutions to specific problems we have to solve.

There is a need spring video Detailed video can focus on my Java exchange group: 901 439 810, we welcome the exchange of learning together

Guess you like

Origin www.cnblogs.com/javahuanhuan/p/11238666.html