Why use Spring
What is Spring
Spring is an open source lightweight Java development framework , designed to improve the efficiency of developers and system maintainability .
One of the biggest goals of Spring is to make JAVA EE development easier. At the same time , Spring and Struts, Hibernate and other single-tier framework is different because Spring is committed to providing a unified , efficient way to structure the entire application , and can be the best combination of single-tier frameworks and kneading together to build a coherent system . It can be said that Spring is a more complete development environment to provide a framework for POJO (Plain Ordinary Java Object) objects to provide enterprise-class services.
Spring Features and Benefits
From the Spring Framework'scharacterizationCome and see:
- Non-intrusive: objects in Spring-based applications can be developed without relying on Spring's APIs
- Inversion of Control: Inversion of Control (IOC), which refers to handing over the creation of objects to Spring to create, is a lightweight IOC container. Before using Spring, the creation of objects are created by ourselves in the code new creation. After using Spring. The creation of objects is given to the Spring framework, which implements theloose coupling。
- Dependency Injection: Dependency Injection (DI), means that the dependent object does not need to manually call the setXX method to set, but through the configuration of the assignment.
- Aspect Oriented Programming: Aspect Oriented Programming (AOP), separating application business logic from system services, and reducing sample code through cutouts and templates.
- Container: Spring is a container that contains and manages the lifecycle of application objects.
- Componentization : Spring implements the use of simple component configuration combined into a complex application . In Spring you can use XML and Java annotations to combine these objects.
- Declarative Transaction Support: Freedom from monotonous and tedious transaction management code, flexible transaction management through a declarative approach that scales down to (e.g., using a single database) local transactions and scales up to global transactions (e.g., using JTA) improves development efficiency and quality.
- One-stop-shop: Based on IOC and AOP, you can integrate various enterprise applications with open source frameworks and good third-party libraries (in fact, Spring itself provides SpringMVC for the presentation layer and Spring JDBC for the persistence layer).
From using the Spring Framework'sdominanceWatch:
- Spring enables developers to use POJOs to develop enterprise-class applications. The advantage of using only POJOs is that you don't need an application server, but you can choose to use a robust servlet container such as Tomcat or some commercial product.
- Spring is organized in a unitary pattern. Even if the number of packages and classes is very large, you only have to worry about the ones you need and ignore the rest.
- Spring will not let you do duplication of effort in vain, it can be integrated with a number of existing technologies, like the ORM framework, logging framework, JEE, Quartz and JDK timers, other view technology.
- Testing an application written in Spring is easy because the environment-related code is moved to this framework. In addition, by using JavaBean-style POJOs, it becomes easier to test data using dependency injection.
- Spring's web framework is a well-designed web MVC framework that provides a good alternative to engineered or less popular web frameworks such as Structs.The MVC pattern leads to the separation of the different aspects of an application (input logic, business logic, and UI logic) while providing loose coupling between these elements. The Model encapsulates the application data, which will typically consist of POJO classes. View (View) is responsible for rendering the model data, generally it generates HTML output that can be interpreted by the client browser. Controller (Controller) is responsible for processing user requests and building the appropriate model and passing it to the view for rendering.
- Spring on JavaEE development is very difficult to use some of the API (JDBC, JavaMail, remote calls , etc.), are provided to encapsulate the application of these APIs to greatly reduce the difficulty .
Relevant information
- official website
- file
- Official github source code
Spring's Components
The Portlet component of the Web module has been deprecated in this release, and the WebFlux component for asynchronous responsive processing has been added.
Introducing from the bottom up
Spring Test
The Spring team promotes test-driven development (TDD). With the help of Inversion of Control (IoC), unit and integration testing becomes easier.
Spring's test module on JUnit (unit testing framework), TestNG (similar to JUnit), Mockito (mainly used to Mock objects), PowerMock (to solve the problems of Mockito such as the inability to simulate the final, static, private methods) and so on the commonly used test framework support are relatively good. And also provides some additional Spring-based testing features , such as in the testing of Web frameworks , simulating the function of Http requests .
incorporateMock Objects, TestContext Framework, Spring MVC Test, WebTestClient。
The corresponding modules of the source code are as follows:
Core Container
The core module of the Spring framework can also be said to be the foundation module, mainly to provide support for IoC dependency injection. By the Beans module, Core core module, Context context module and SpEL expression language module , without these core containers , it is not possible to have AOP, Web and other upper layer functions.
- spring-core: Encapsulates the underlying parts of the Spring framework , including resource access , type conversion and some common tools .
- spring-beans: Provides support for creating, configuring, and managing beans, including control inversion and dependency injection.
- spring-contextApplicationContext: builds on the Core and Beans modules, integrating the Beans module functionality and adding resource binding, data validation, internationalization, Java EE support, container lifecycle, event propagation, etc. The ApplicationContext interface is the focal point of the Context module.
- spring-expression: Provides support for the Spring Expression Language (SpEL), which depends only on the core module and no other modules, and can be used independently. Support for accessing and modifying property values , method calls , support for accessing and modifying arrays , containers and indexers , named variables , support for arithmetic and logical operations , support for obtaining beans from the Spring container , it also supports list projection , selection and general list aggregation.
The corresponding source code modules are listed below:
AOP, Aspects, Instrumentation and Messaging
- spring-aspects: This module provides support for integration with AspectJ, a powerful and mature cutter-oriented programming (AOP) framework.
- spring-aop: Provides a cutter-oriented programming implementation . Provide , for example, logging , permission control , performance statistics and other general functions and business logic separation of technology , and can dynamically add these functions to the code needed , so that each division of responsibility , reduce the business logic and general function of the coupling .
- spring-instrument: Provides the ability to add an agent to the JVM. Specifically, it provides a weaving agent for Tomcat that can pass class files to Tomcat as if they were loaded by a class loader. It doesn't matter if you don't understand it, there are very limited scenarios where this module can be used.
- spring-messaging: A new module from Spring 4.0, the main responsibility is to integrate some basic messaging applications for the Spring framework.
- spring-jcl module: A new module for logging framework integration has been added to Spring.
The corresponding source code modules are listed below:
Data Access/Integration
- spring-jdbc: Provides an abstraction of JDBC for database access. different databases have their own separate APIs for manipulating databases, and Java programs only need to interact with the JDBC API, which shields them from database influence.
- spring-tx: Supports programmatic and declarative transaction management.
- spring-orm: Provides support for ORM frameworks such as Hibernate, JPA, iBatis and MyBatis. And you can also use Spring transaction management , no additional control of transactions .
- spring-oxm: Provide an abstraction layer to support OXM (Object-to-XML-Mapping), e.g. JAXB, Castor, XMLBeans, JiBX and XStream. Mapping Java objects to XML data or mapping XML data to Java objects.
- spring-jms : refers to the Java Message Service, which provides a set of "message producer, message consumer" templates for simpler use of JMS, which is used to send messages for asynchronous communication between two applications, or in distributed systems. Since Spring Framework 4.1, it also provides inheritance to the spring-messaging module.
Corresponds to the source module:
Spring Web
- spring-web: Provides basic Web development integration features such as multi-file upload capabilities, IOC container initialization using Servlet listeners, and Web application contexts.
- spring-webmvcThe Spring MVC framework provides annotation-based injection of request resources , simpler data binding , data validation , etc. and a set of very easy to use JSP tags , completely seamless with the rest of the Spring technology .
- spring-websocket: Provides support for WebSocket, which allows two-way communication between a client and a server.
- spring-webflux: Provides support for WebFlux, the new responsive framework introduced in Spring Framework 5.0. Unlike Spring MVC, it does not require a Servlet API, is fully asynchronous, and implements the Reactive Streams specification through the Reactor project.Spring WebFlux is used to create fully asynchronous and non-blocking applications based on an event loop execution model.
The corresponding source code modules are listed below:
Relationship between Spring, SpringMVC, SpringBoot
Spring contains a number of functional modules (mentioned above), the most important of which is Spring-Core (which provides support for IoC dependency injection) module, the implementation of other modules in Spring (such as Spring MVC) basically need to rely on this module.
Spring MVC is a very important module in Spring, mainly to give Spring the ability to quickly build MVC architecture of the Web program.MVC is the model (Model), view (View), controller (Controller) of the abbreviation, the core idea is to organize the code through the separation of the business logic, data, display.
Using Spring to develop various configurations is too cumbersome, for example, to enable certain Spring features, you need to explicitly configure them in XML or Java. Thus, Spring Boot was born!
Spring is designed to simplify J2EE enterprise application development.Spring Boot is designed to simplify Spring development (fewer configuration files, out of the box!). Spring Boot is designed to simplify Spring development (fewer configuration files, out of the box!).
Spring Boot just simplifies the configuration, if you need to build MVC architecture of the Web program, you still need to use Spring MVC as the MVC framework, just that Spring Boot helps you simplify a lot of Spring MVC configuration, really out of the box!
HelloWorld-xml
This is just the first Spring project, labeled HelloWorld. The actual requirement is to get the list of users and print the execution log.
case (law)
Click on the case source codehere are
- Introducing dependencies
<properties>
<>8</>
<>8</>
<>5.3.37</>
<>1.9.6</>
</properties>
<dependencies>
<dependency>
<groupId></groupId>
<artifactId>spring-context</artifactId>
<version>${}</version>
</dependency>
<dependency>
<groupId></groupId>
<artifactId>spring-core</artifactId>
<version>${}</version>
</dependency>
<dependency>
<groupId></groupId>
<artifactId>spring-beans</artifactId>
<version>${}</version>
</dependency>
<dependency>
<groupId></groupId>
<artifactId>aspectjweaver</artifactId>
<version>${}</version>
</dependency>
</dependencies>
- POJO - User
public class User {
private String name;
private int age;
public User(String name, int age) {
= name;
= age;
}
public String getName() {
return name;
}
public void setName(String name) {
= name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
= age;
}
}
- DAO gets POJO, UserDaoServiceImpl (mock data)
public class UserDaoImpl{
public List<User> findUserList() {
return (new User("seven", 18));
}
}
- Business Layer UserServiceImpl (calling the DAO layer)
public class UserServiceImpl {
private UserDaoImpl userDao;
public void setUserDao(UserDaoImpl userDao) {
= userDao;
}
public List<User> findUserList() {
return ();
}
}
- Intercepts all methods in the service and outputs logging
@Aspect
public class LogAspect {
@Around("execution(* .*.*(..))")
public Object businessService(ProceedingJoinPoint pjp) throws Throwable {
// get attribute through annotation
Method method = ((MethodSignature) ()).getMethod();
("execute method: " + ());
// continue to process
return ();
}
}
- Add and add and
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
xmlns:xsi="http:///2001/XMLSchema-instance"
xsi:schemaLocation="/schema/beans /schema/beans/">
<bean class="">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<bean class="">
<property name="userDao" ref="userDao"/>
<!-- additional collaborators and configuration for this bean go here -->
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
xmlns:xsi="http:///2001/XMLSchema-instance"
xmlns:aop="/schema/aop"
xmlns:context="/schema/context"
xsi:schemaLocation="/schema/beans
/schema/beans/
/schema/aop
/schema/aop/
/schema/context
/schema/context/
">
<context:component-scan base-package="" />
<aop:aspectj-autoproxy/>
<bean class="">
<!-- configure properties of aspect here as normal -->
</bean>
<!-- more bean definitions for data access objects go here -->
</beans>
- Setting up xml files in APP
public class APP {
public static void main(String[] args) {
// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("", "");
// retrieve configured instance
UserServiceImpl service = ("userService", );
// use configured instance
List<User> userList = ();
// print info from beans
(a -> (() + "," + ()));
}
}
Run results:
How to demonstrate the advantages of Spring
Inversion of Control - IOC
user search(service by calling dao query pojo), essentially how to create User/Dao/Service?
- If you don't have the Spring Framework, you need to create your own User/Dao/Service, etc., for example:
UserDaoImpl userDao = new UserDaoImpl();
UserSericeImpl userService = new UserServiceImpl();
(userDao);
List<User> userList = ();
- With the Spring Framework, you can transfer the creation of the original bean to the framework, when you need to use the container from the bean can be obtained, which simplifies the development of work
Bean creation and usage are separated.
// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("", "");
// retrieve configured instance
UserServiceImpl service = ("userService", );
// use configured instance
List<User> userList = ();
Further.Then you can understand why there are knowledge points such as the following:
- The Spring Framework manages the creation of these beans, i.e., the user-managed bean is transformed into a framework-managed bean, which is called theInversion of Control (IoC)
- Where are the beans created by the Spring Framework hosting placed? This isIoC Container;
- The Spring framework, in order to better allow users to configure beans, necessarily introduces theWhat are the different ways to configure a bean? These are xml configuration, Java configuration, annotation configuration, and so on.equal support
- Since the Spring framework takes over the generation of the bean, it necessarily needs toManaging the entire bean lifecycleetc;
- The application code gets the dependent beans from the Ioc Container and injects them into the application, a process calledDependency Injection (DI) So control inversion is realized through dependency injection, but they are actually different perspectives of the same concept. In layman's terms.IoC is the design idea, DI is the implementation
- What are the ways when it comes to dependency injection? This is the constructor approach, @Autowired, @Resource, @Qualifier... At the same time there are dependencies between beans (there may be order of precedence issues, as well ascircular dependency problemetc.)
Cutting-oriented - AOP
The second demand:Add logging to all Service method calls(when calling a method), which is essentially a decoupling problem;
- If you don't have the Spring Framework, you need to add logging methods to each service's methods, for example:
public List<User> findUserList() {
("execute method findUserList");
return ();
}
- With the Spring Framework, through the @Aspect annotation Define the cutout, the cutout is defined to intercept all the methods in the service, and logging; it can be clearly seen that the framework will be logging and business requirements of the code decoupled, no longer intrusive
/**
* aspect for every methods under service package.
*/
@Around("execution(* .*.*(..))")
public Object businessService(ProceedingJoinPoint pjp) throws Throwable {
// get attribute through annotation
Method method = ((MethodSignature) ()).getMethod();
("execute method: " + ());
// continue to process
return ();
}
Further.Then you can understand why there are knowledge points such as the following:
- The Spring Framework decouples different business modules by defining facets and intercepting cutpoints.Aspect Oriented Programming - Aspect Oriented Programming (AOP)
- Why does the @Aspect annotation use the aspectj jar package? This leads us to theThe History of Aspect4J and Spring AOPThe only way to understand the origins of Aspect4J and Spring is to understand that some of the annotations are compatible with the design.
- How to supportMore ways to interceptWhat about decoupling for more scenarios? This is where @Around, @Pointcut... etc.
- So how does the Spring Framework implement AOP? This introducesProxy technology, divided into static and dynamic proxiesThe dynamic agents include the JDK agent and the CGLIB agent.
Spring Framework Step-by-Step Simplified Development
Java Configuration Modification
Click on the case source codehere are
In the previous example, the xml configuration is implemented in a way that is actually quite cumbersome; I transformed it through Java configuration:
- User, UserDaoImpl, UserServiceImpl, LogAspect don't need to be changed.
- Convert the original configuration via .xml to Java configuration
@EnableAspectJAutoProxy
@Configuration
public class BeansConfig {
/**
* @return user dao
*/
@Bean("userDao")
public UserDaoImpl userDao() {
return new UserDaoImpl();
}
/**
* @return user service
*/
@Bean("userService")
public UserServiceImpl userService() {
UserServiceImpl userService = new UserServiceImpl();
(userDao());
return userService;
}
/**
* @return log aspect
*/
@Bean("logAspect")
public LogAspect logAspect() {
return new LogAspect();
}
}
- Loading the BeansConfig configuration in the app
public class APP {
public static void main(String[] args) {
// create and configure beans
ApplicationContext context = new AnnotationConfigApplicationContext();
// retrieve configured instance
UserServiceImpl service = ("userService", );
// use configured instance
List<User> userList = ();
// print info from beans
(a -> (() + "," + ()));
}
}
The principle of implementation is briefly mentioned here:
-
When the application starts, the Spring Framework uses Java's Reflection API to check all of the data with the
@Configuration
annotated classes (here's a good place to look if you don't understand)Principles of Annotation Implementation). The Spring Framework has a built-in annotation handler.ConfigurationClassPostProcessor
It'sBeanFactoryPostProcessor
A realization of the -
in one's turn
ConfigurationClassPostProcessor
will be called when the container is initialized, and it will look for all the objects with the@Configuration
annotated classes, and parses the@Bean
Methods.-
BeanDefinition: For each
@Configuration
class, Spring will create a new class for each of the@Bean
method generates aBeanDefinition
Object. TheseBeanDefinition
object will contain all the information needed to create and configure the bean. -
Handling nested configurations: If a
@Configuration
The class contains another@Configuration
class reference.ConfigurationClassPostProcessor
will recursively process these nested configuration classes.
-
-
Register BeanDefinition: Once all the
BeanDefinition
are created, they are registered with the Spring container'sBeanFactory
in the Spring container. This allows the Spring container to create and inject these beans when needed. -
Proxy Configuration Class: In order to support features such as nested configuration classes and cyclic dependencies, Spring creates a new configuration class for every
@Configuration
class creates a proxy that handles the logic at runtime.
Annotation Configuration Method Modification
Click on the case source codehere are
Further, Java 5 began to provide annotation support, and Spring 2.5 began to fully support annotation-based configuration and also supported the JSR250 annotation. Subsequent versions of Spring have favored the use of annotations in conjunction with Java configuration.
- BeanConfig no longer requires Java configuration
@EnableAspectJAutoProxy
@Configuration
public class BeansConfig {
}
- UserDaoImpl added @Repository annotation
@Repository
public class UserDaoImpl{
public List<User> findUserList() {
return (new User("seven", 18));
}
}
- UserServiceImpl adds the @Service annotation and injects the userDao via @Autowired.
@Service
public class UserServiceImpl {
@Autowired
private UserDaoImpl userDao;
public List<User> findUserList() {
return ();
}
}
- Logging class adds @Component annotation
@Component
@Aspect
public class LogAspect {
@Around("execution(* .*.*(..))")
public Object businessService(ProceedingJoinPoint pjp) throws Throwable {
// get attribute through annotation
Method method = ((MethodSignature) ()).getMethod();
("execute method: " + ());
// continue to process
return ();
}
}
- Scanning packages in the app
public static void main(String[] args) {
// create and configure beans
ApplicationContext context = new AnnotationConfigApplicationContext("");
// retrieve configured instance
UserServiceImpl service = ();
// use configured instance
List<User> userList = ();
// print info from beans
(a -> (() + "," + ()));
}
One thing to mention here is that this is basically the way most Spring projects, these days, work. The main steps are:
1, add @Component-related annotations to the class, such as @Controller, @Service, @Repository
2. Set the basePackage of ComponentScan, for example, in the xml file.<context:component-scan base-package=''>
, or set it in the configuration class@ComponentScan("")
annotation, or directly in the app classnew AnnotationConfigApplicationContext("")
Specifies the basePackage to scan.
SpringBoot Managed Configuration
Springboot actually by convention over configuration , the use of xx-starter unified default initialization of beans , the user only needs very little configuration can be developed .
Interview questions column
Java interview questions columnIt's online, so feel free to visit.
- If you don't know how to write a resume, resume projects don't know how to package them;
- If there's something on your resume that you're not sure if you should put on it or not;
- If there are some comprehensive questions you don't know how to answer;
Then feel free to private message me and I will help you in any way I can.