Spring learning notes-01

Mulavar 2021-02-23 17:43:25
spring learning notes-01 notes


1. Spring brief introduction

One sentence summary Spring,Spring It's an open source 、 A lightweight Inversion of control (IOC) and Section oriented programming (AOP) Framework .

1.1 Spring、SpringMVC、Spring Boot and Spring Cloud The difference between

SpringMVC Is in Spring On the basis of the combination of MVC Three tier framework , Use DispatchServlet And view parser make view jump and controller scheduling more convenient , Mainly responsible for handling WEB application development .SpringMVC yes Spring A submodule .

SpringBoot It uses Convention over configuration Idea , To simplify the Spring To configure , Focus on the development of micro Services .

SpringCloud Focus on the integration of global microservices 、 management .

2. Inversion of control —IOC

2.1 Basic concepts

IOC: Inversion of control , It's a design idea . namely Transfer control of object creation to Spring Containers .

Suppose we create a class A, class A There is a member variable class in B.

  • Traditional development : We need to create the class manually B The object of , Assign him to a class A The object of , This is called active control object creation ;
  • IOC:Spring Create good B object , Then store it in a container , When A Object needs to use B Object time ,Spring Take it out of the container where the object is stored A The one to use B object .

Using traditional methods ,A Yes B There is dependence , That is to say A and B There is a coupling relationship between ( hypothesis B The implementation of has been changed , We may need to change it A Source code ), And by IOC Thought , This dependency is replaced by a container , The creation of all objects depends on the container , At startup ,Spring Will read the configuration file , And inject the created object into the container first , After that, we want to use it and take it directly from the container .

DI: Dependency injection , It can be understood as Spring Realization IOC In a specific way .

2.2 Spring How to create objects

class UserService {
private UserDao dao;
public void setUserDao(UserDao dao) {
this.userDao = dao;
}
}
class UserDao {
private String name;
public void setName(String name) {
this.name = name;
}
}

2.2.1 Constructors

<bean id="dao" class="com.dong.dao.UserDao">
<!-- Use name Positioning constructor -->
<constructor-arg name="name" value="dongjh"></constructor-arg>
</bean>
<bean id="service" class="com.dong.service.UserService">
<!-- Use type Positioning constructor -->
<constructor-arg type="com.dong.dao.UserDao" ref="dao"></constructor-arg>
</bean>

notes :

  1. If a class has a parameterless construction method , The parameterless construction method is called by default ;
  2. If a class has only one constructor , The constructor is called by default .

2.2.2 property( call set Method creation )

<bean id="dao" class="com.dong.service.UserDao">
<!-- Basic types use value Injection properties -->
<property name="name" value="dongjh"></property>
</bean>
<bean id="service" class="com.dong.service.UserService">
<!-- Reference types use ref attribute -->
<property name="userDao" ref="dao"></property>
</bean>

notes :

  1. When using property injection , The container will By default, the parameterless construction method is called to create an instance , So you need to make sure that the bean Construction method with or without parameters ;
  2. Using property injection is equivalent to calling setXXX Method ,XXX yes property In the tag name, Let's assume that the above code is correct setName The method was changed to setName1, Is the first bean Of property It needs to be written like this :
<property name="name1" value="dongjh"></property>

2.3 Bean Automatic assembly of (autowiring)

Automatic assembly Spring Automatically find in context , Automatic feed bean Assembly properties .

bean There are three main strategies for automatic assembly :

  1. byname: To associate with bean(A) attribute With the same name Other bean(B) Automatically assemble to the bean(A) Properties of ;
  2. byType: To associate with bean(A) attribute With the same type Other bean(B) Automatically assemble to the bean(A) Properties of ;
  3. constructor: To associate with bean(A) The constructor of With the same type Other bean(B) Automatically assemble to the bean(A) Properties of ;

2.3.1 byName

xml Configuration mode
<!-- Because of the bean Of id by userDao, So it will be directly and automatically assembled below service Of userDao Properties of the -->
<bean id="userDao" class="com.dong.service.UserDao">
<property name="name" value="dongjh"></property>
</bean>
<!-- There are setUserDao Method , And set the property of automatic assembly byName-->
<bean id="service" class="com.dong.service.UserService" autowired="byName">
</bean>

2.3.2 byType

xml Configuration mode
<!-- The bean The type of com.dong.service.UserDao, So it will be directly and automatically assembled below service Of userDao Properties of the -->
<bean id="userDao111" class="com.dong.service.UserDao">
<property name="name" value="dongjh"></property>
</bean>
<!-- This class has one com.dong.service.UserDao Properties of type , And set the property of automatic assembly byType-->
<bean id="service" class="com.dong.service.UserService" autowired="byType">
</bean>

2.4 Spring Annotation configuration

JDK1.5 Start supporting annotations , and Spring yes 2.5 Start supporting .

Use Spring Annotation configuration needs to import constraints first : context Namespace and annotation scanning .

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- notes : Only annotations defined in the same application context are found ,
For example, put the statement in the DispatcherServlet In the configuration context of ,
It just checks controllers The context of , Instead of checking services The context of ,
For details, see https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-annotation-config-->
<context:annotation-config/>
<!-- Specify annotation scan return -->
<context:component-scan base-package="com.dong.dao"></context:component-scan>
</beans>

@Autowired

After that, in the need of automatic assembly Attribute or set Method Upper use @AutoWired annotation , Then automatic assembly can be realized .

// Detailed modifiable scope
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})

notes :@Autowired Will use first byType, Press again byName Automatic assembly in sequence .

@Autowired There is a common attribute :required, The default value is true, This property indicates whether the decorated member variable must be assembled with one bean:

  • When required Set to true when , Indicates that there must be one that can be automatically assembled to the member variable bean, Otherwise, the report will be wrong ;
  • When required Set to false when , Indicates that the member variable can be null;

@Qualifier

When there is more than one bean When automatic assembly conditions are met , You can use the bean, General coordination @Autowired Use .

@Qualifier There's a property value, Here it is value Set the assembly you want to assemble bean Of id that will do .

@Component

decorator , Indicates that the bean Object injected into Spring In the container .

@Component There's a property value, Represents the value set at the time of injection id.

Such as :

// Equivalent to <bean id="user" class="User">
@Component(value="user")
public class User {}

@Component There are some derived annotations , Such as Web Development will follow MVC Architecture layering , According to different functional layers , Some notes have been derived :

  • @Repository: in the light of dao layer
  • @Service: in the light of service layer
  • @Controller: in the light of controller layer

These four annotations have the same function , All of them indicate that the bean Object injected into Spring In the container .

@Value

Inject values into properties , It is mainly used to inject values into member variables , Simple can Injects the value of the base type , When it's complex, you can inject some operating system properties or other properties bean Properties of .

@Scope

Used for setting up bean Scope of action , Let's start with the most common :

  • singleton: Globally unique , Single case ;
  • prototype: Each injection creates a new object .

The difference between annotation and configuration

xml More powerful , Easy to manage and maintain . Annotations are suitable for simple attribute injection .

2.5 JavaConfig To configure

Spring 3.0 After that, we started to support a better configuration : be based on Java Class configuration . By increasing the @Configuration The annotation indicates that this is a configuration class , Its bottom layer is @Component( That is, the bean The object will be Spring Container nozzle ).

@Configuration combination @Bean Annotations can be implemented XML Configure to implement the function of injection , Effect and

<beans>
<bean>...</bean>
<bean>...</bean>
</beans>

similar , In the use of @Bean When the annotation , Indicates that the object returned by this method is loaded into the Spring Containers , In the use of @Bean Attention should be paid when modifying methods :

  1. Method with return value , And the return type is to be managed bean The type of ;
  2. The method name is the default bean name, You can use @Bean Of name Attribute customization ;
  3. The method can take parameters , be In this case, the passed in parameter must also be the passed in parameter Spring container-managed bean.

In order to create UserService and UserDao For example :

@Configuration
public class UserConfiguration {
@Bean
public UserService userService() {
return new UserService();
}
@Bean
public UserDao userDao() {
return new UserDao();
}
}

When Spring When scanning this class , Will automatically UserConfiguration、UserService、UserDao Of bean Injection into Spring Hosting in a container .

3. Section oriented programming —AOP

3.1 Basic concepts

In software development , We need to write a lot of business code , But there's a lot of code that's business independent , Such as

  • Log function
  • Cache cleanup
  • Recycling
  • Permission check

In order to realize the separation of business code and non business code ,Spring The non business code is extracted by proxy pattern , To form the AOP thought .

AOP Full name Aspect Oriented Programming, Aspect oriented programming , Suppose the business code itself is a vertical logical flow , We're looking for a few of them ( Tangent point ,Pointcut), Insert non business code , It's like sections (Aspect), That's a simple one AOP Example .

It's easy to confuse tangent plane and tangent point , Strictly speaking , The tangent point is part of the information of the section , The section contains two parts of information :

  • The breakthrough point ;
  • Action to be performed after cut in (Advice).

But in the concrete realization ,Spring Add a message to the section : At which stage of the tangent point ? From this, we can see that :

  • Pre notice (Before): Calling the notification function before the target method is invoked ;
  • The rear notice (After): Calling the notification function after the target method is invoked ;
  • Return to inform (After-returning): Call notification after successful execution of target method ;
  • Abnormal notice (After-throwing): Call notification after object method throws exception ;
  • Surrounding the notification (Around): The notification package contains the method to be notified , Custom behavior is performed before and after the notified method invocation .

About AOP stay Spring There are three ways to achieve this :

  1. Implement native Spring API Interface
  2. Custom facet class
  3. annotation

3.2 Realizing native Spring API Interface

Spring Provides information such as MethodBeforeAdvice、AfterAdvice、AfterReturningAdvice And other native interfaces , We can build facets by implementing these interfaces , Such as

@Component
public class Log implements MethodBeforeAdvice {
/**
* @param method Target object method to execute
* @param objects Parameters
* @param o Target audience
* @throws Throwable
*/
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName() + "-" + method.getName() + " Will be implemented ");
}
}

The Log Class implements the MethodBeforeAdvice, Becomes a facet inserted before the method executes , secondly , We need to be in XML To configure , Set the tangent point and establish its connection with the tangent plane :

<aop:config>
<!-- The breakthrough point :execution expression ,execution( The method to be executed !)-->
<aop:pointcut id="pointcut" expression="execution(* com.dong.service.UserServiceImpl.*(..))"/>
<aop:advisor advice-ref="log" pointcut-ref="pointcut"></aop:advisor>
</aop:config>

execution Indicates that it is triggered when the method is executed ;* The return value of the representation method can be of any type ,com.dong.service.UserServiceImpl.* Use the fully qualified class name and method name to specify the method to add the pre notification , Use * Said to com.dong.service.UserServiceImpl All methods under the class perform the cut in ;(..) Represents a list of parameters for a method , Use (..) The input parameter of the representation method can be of any type .

We need to pay attention to ,Log It has to be a victim Spring container-managed bean object , otherwise Spring You will not be able to find the location of the section bean, Therefore use @Component To modify ( You can also use XML Configuration, etc ).

3.3 Custom facet class

Custom facets do not need to be implemented Spring The native interface of , First, you need to define a section class , And load the Spring The container is hosted .

@Component(value="diy")
public class DiyPointCut {
public void before() {
System.out.println(" Before method execution ");
}
public void after() {
System.out.println(" After method execution ");
}
}

And 3.2 be similar , This method needs to be passed XML Configuration sets the tangent point and its connection to the tangent plane .

<aop:config>
<!-- Custom facets ,ref: To reference bean-->
<aop:aspect ref="diy">
<aop:pointcut id="pointcut" expression="execution(* com.dong.service.UserServiceImpl.*(..))"/>
<!-- Appoint advice The relation between the tangent point and the tangent point -->
<aop:before method="before" pointcut-ref="pointcut"></aop:before>
<aop:after method="after" pointcut-ref="pointcut"></aop:after>
</aop:aspect>
</aop:config>

3.4 annotation

3.4.1 Enable annotation

First , There are two ways to use annotations :

  1. XML Import configuration :

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    https://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- Enable annotation -->
    <context:annotation-config/>、
    <!-- Annotation package scan -->
    <context:component-scan base-package="com.dong.dao"></context:component-scan>
    <context:component-scan base-package="com.dong.log"></context:component-scan>
    <!-- Enable aop annotation -->
    <aop:aspectj-autoproxy proxy-target-class="true"/>
    </beans>
  2. Use @EnableAspectJAutoProxy Annotate the classes that need to be cut

    @Component(value = "userService")
    @EnableAspectJAutoProxy
    public class UserServiceImpl implements UserService {}

secondly , When using annotations , There are two parts to note :

  • Statement face to face : Declare that a class is a section and the actual action to be performed after the cut (Advice);
  • Locating the tangent point : Need to pass through execution The method of expression positioning needs to be cut in .

Here's how to use annotations .

3.4.2 Annotations use

Use only one class @Aspect To modify , It shows that this is a section . You can use one of these methods

  • @Before
  • @After
  • @AfterReturning
  • @Around
  • @AfterThrowing

Note specifies the cut in time , Entry point through execution Expression assignment , Examples are as follows :

@Aspect
@Component
public class CustomPointCut {
@Before("execution(* com.dong.service.UserServiceImpl.*(..))")
public void before() {
System.out.println("aop: Before the method occurs ");
}
}

4. Reference material

  1. Spring newest 5 Full tutorial
  2. Spring introduction ( Ten ):Spring AOP Use and explain
  3. Spring AOP - How to use annotation
版权声明
本文为[Mulavar]所创,转载请带上原文链接,感谢
https://javamana.com/2021/02/20210223173210495o.html

  1. 忘记云服务器上MySQL数据库的root密码时如何重置密码?
  2. Detailed explanation of lettuce, an advanced client of redis
  3. Springboot learning integrated application (1)
  4. Linux File Recover
  5. Linux-Security
  6. How to reset the password when you forget the root password of MySQL database on the cloud server?
  7. Linux File Recover
  8. Linux-Security
  9. LiteOS:盘点那些重要的数据结构
  10. Linux Memory
  11. Liteos: inventory those important data structures
  12. Linux Memory
  13. 手把手教你使用IDEA2020创建SpringBoot项目
  14. Hand in hand to teach you how to create a springboot project with idea2020
  15. spring boot 整合swagger2生成API文档
  16. Spring boot integrates swagger2 to generate API documents
  17. linux操作系统重启后 解决nginx的pid消失问题
  18. Solve the problem of nginx PID disappearing after Linux operating system restart
  19. JAVA版本号含义
  20. The meaning of java version number
  21. 开源办公开发平台丨Mysql5.7两套四节点主从结构环境搭建教程(二)
  22. 开源办公开发平台丨Mysql5.7两套四节点主从结构环境搭建教程(一)
  23. Open source office development platform mysql5.7 two sets of four node master-slave structure environment building tutorial (2)
  24. HTTP的“无状态”和REST的“状态转换”
  25. Open source office development platform mysql5.7 two sets of four node master-slave structure environment building tutorial (1)
  26. 【大数据哔哔集20210128】使用Hive计算环比和同比
  27. 【大数据哔哔集20210125】Kafka将逐步弃用对zookeeper的依赖
  28. 【大数据哔哔集20210124】有人问我Kafka Leader选举?我真没慌
  29. 【大数据哔哔集20210123】别问,问就是Kafka高可靠
  30. Spring 事务、异步和循环依赖有什么关系?
  31. Spring 动态代理时是如何解决循环依赖的?为什么要使用三级缓存?
  32. "Stateless" of HTTP and "state transition" of rest
  33. [big data bibiji 20210128] use hive to calculate month on month and year on year
  34. [big data bibiji 20210125] Kafka will gradually abandon its dependence on zookeeper
  35. [big data beeps 20210124] someone asked me about Kafka leader election? I'm not in a panic
  36. [big data bibiji 20210123] don't ask, ask is Kafka highly reliable
  37. jQuery Gantt Package 在Visual Studio中创建一个新的ASP.NET项目
  38. What is the relationship between spring transactions, asynchrony, and circular dependencies?
  39. How to solve circular dependency in spring dynamic proxy? Why use level 3 caching?
  40. Unicode码的二进制转换(Java)
  41. JAVA的函数式接口
  42. JAVA里的元祖类
  43. JQuery Gantt package to create a new ASP.NET project
  44. Binary conversion of Unicode code (Java)
  45. The functional interface of Java
  46. Yuanzu class in Java
  47. Java中的CPU占用高和内存占用高的问题排查
  48. HashMap连环问你能答出几道?
  49. IntelliJ IDEA 还能画思维导图,果然最强 IDE!
  50. java中的反射和代理
  51. Troubleshooting of high CPU and memory usage in Java
  52. How many questions can you answer?
  53. IntelliJ idea can also draw mind maps. It's really the strongest ide!
  54. Reflection and proxy in Java
  55. Java中的CPU占用高和内存占用高的问题排查
  56. Linux OOM(out of memory)
  57. mysql 自定义函数因参数名称报错
  58. Troubleshooting of high CPU and memory usage in Java
  59. Linux OOM(out of memory)
  60. MySQL user defined function error due to parameter name