preface
BiliBili watches videos and learns Java with crazy God. After watching spring and mybtis, if you don't organize your notes, you really forget before learning and after learning. You can follow the progress when learning. After that, you will have a hand without practicing This article is crazy God's notes + personal summary
Thank you @ crazy God for saying that open resources give more people who love learning opportunities
Tip: the following is the main content of this article. The following cases can be used for reference
1, Spring
1.maven version download address: https://archive.apache.org/dist/maven/
2.Spring version official download address: https://repo.spring.io/release/org/springframework/spring/
3.maven relies on warehouse: https://mvnrepository.com/
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.8</version> </dependency>
2, Use
1. Advantages
Spring is an open source, free framework (container)
Spring is a lightweight, non intrusive framework
Two features: control inversion (IOC) and aspect oriented (AOP)
Support declarative transactions and integrate the framework
2. Composition of spring
Spring-Core:
The Core package is the most basic part of the framework and provides the Dependency Injection management Bean container function. The basic concept here is BeanFactory, which provides a classic implementation of Factory pattern to eliminate the need for procedural singleton pattern, and really allows you to separate dependencies and configurations from program logic.
Spring context: (spring core container < context module >)
The BeanFactory of the core module makes Spring a container, while the context module makes it a framework. This module extends the concept of BeanFactory and adds support for message, event propagation and verification. In addition, this module provides many enterprise services, such as e-mail, JNDI access, EJB integration, remote and scheduling services. It also includes support for template frameworks such as Velocity and FreeMarker integration.
Spring-Aop:
Spring provides rich support for aspect oriented programming in its AOP module. For example, method interceptors (servletlistener, controller...) and pointcuts can effectively prevent the coupling of functions in the code. This module is the basis for implementing aspect programming in spring applications. Spring's AOP module also introduces metadata programming into spring. Using spring's metadata support, you can add comments to your source code to indicate where and how spring applies aspect functions.
Spring-Dao:
Using JDBC often leads to a lot of duplicate code. Obtaining connections, creating statements, processing result sets, and then closing connections, and migrating custom tool classes from old code. JDBC util also makes development cumbersome. Spring's Dao module abstracts the traditional JDBC and provides a better declarative transaction management method than programming.
Spring-Web:
The Web context module is built on the application context module and provides the basic integration features of web development, such as file upload. In addition, this module also provides some service-oriented support. Use Servlet listeners for IOC container initialization and application context for web.
Spring Web MVC:
(model view controller) Spring provides a fully functional MVC framework for building Web applications. It provides a clear separation model between domain model code and web form. Also, you can take advantage of other features of the Spring framework.
Spring-ORM:
The ORM package provides an integration layer for the popular "relationship / object" mapping APIs, including JDO, Hibernate and iBatis (MyBatis). Through the ORM package, you can mix all the features provided by Spring for "object / relationship" mapping to facilitate the integration of code within the team during development.
2. Implementation of IOC
UserDao interface
UserDaoImpl interface implementation
UserService business interface
UserServiceImpl business implementation
//Interface objects declared in UserServiceImpl private UserDao userDao; //Dynamic value injection using set public void setUserDao(UserDao userDao) { this.userDao = userDao; }
applicationContext.xml 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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <!--Create an implementation class bean object--> <bean id="UserDaoOraclelImpl" class="com.kuang.dao.UserDaoOraclelImpl"/> <bean id="UserServiceImpl" class="com.kuang.service.UserServiceImpl"> <!-- ref quote spring Created in container bean object value Specific value basic data type --> <property name="userDao" ref="UserDaoOraclelImpl"/> </bean> </beans>
Test class
//Get the context object of Spring ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //Objects are managed in Spring and are taken out directly when used UserService userService= context.getBean("UserServiceImpl",UserService.class);
3. Summary of control reversal
The new object in the program is controlled by the programmer,
spring uses xml or annotation, set method (DI dependency injection),
The IOC container implements control inversion
It reduces the coupling of the system and can focus on business implementation
3, xml usage
1.list.map.set.array p.c tag
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <!--Import other profiles--> <import resource="beans.xml"/> <!--P Can be injected directly--> <bean id="user" class="com.kuang.pojo.User" p:name="Li Si" p:age="26"/> <!--C Constructor injection with or without parameters constructor-arg--> <!--scope="prototype" bean Scope of scope Default singleton singleton Can not write,prototype Prototypes generate new objects each time--> <bean id="user2" class="com.kuang.pojo.User" c:age="18" c:name="Zhang San" scope="prototype"/> <bean id="address" class="com.kuang.pojo.Address"> <property name="address" value="Xi'an"/> </bean> <bean id="student" class="com.kuang.pojo.Student"> <!--First kind set injection name/value--> <property name="name" value="Loulan"/> <!--Second bean injection name/ref--> <property name="address" ref="address"/> <!--Array injection --> <property name="books"> <array> <value>The Dream of Red Mansion</value> <value>Water Margin</value> <value>Romance of the Three Kingdoms</value> <value>Journey to the West</value> </array> </property> <!--List injection --> <property name="hobbys"> <list> <value>listen to the music</value> <value>Knock code</value> <value>watch movie</value> </list> </property> <!--Map injection --> <property name="card"> <map> <entry key="ID" value="666666666666666666"/> <entry key="bank card" value="777777777777777777"/> <entry key="XXX" value="123123"/> </map> </property> <!--Set injection--> <property name="games"> <set> <value>LOL</value> <value>CF</value> <value>DNF</value> </set> </property> <!--null injection--> <property name="wife" > <null/> </property> <!--Properties --> <property name="info"> <props> <prop key="Student number">666666</prop> <prop key="full name">Balabala</prop> <prop key="Gender">male</prop> <prop key="hobby">ha-ha</prop> </props> </property> </bean> </beans>
2.IOC assignment method
<!--First subscript assignment Parametric structure --> <bean id="User" class="com.kuang.pojo.User"> <constructor-arg index="0" value="Li Si"></constructor-arg> </bean> <!--The second is created by type If multiple parameters are not recommended --> <bean id="User" class="com.kuang.pojo.User"> <constructor-arg type="java.lang.String" value="Zhang San" ></constructor-arg> </bean> <!--The third parameter name is set directly through the parameter name --> <bean id="User" class="com.kuang.pojo.User"> <constructor-arg name="name" value="Wang Wu"/> </bean> <!--When the configuration file is loaded bean Has been created and initialized--> <bean id="UserT" class="com.kuang.pojo.UserT"> </bean>
3.Autwired annotation support
Auto assemble byName and byType autowire = "byName"
<bean id="dog" class="com.kuang.pojo.Dog"/> <bean id="dog222" class="com.kuang.pojo.Dog"/> <bean id="cat" class="com.kuang.pojo.Cat"/> <!-- byName Automatically looks in the container context,And their own objects set Method bean id byType Automatically looks in the container context,The same property type as your own object bean --> <bean id="people" class="com.kuang.pojo.People" autowire="byType"> <property name="name" value="loong"/> </bean>
When byName, you need to ensure that the IDs of all beans are unique, and the bean needs to be consistent with the value of the set method of the automatically injected attribute!
When byType, you need to ensure that the class of all beans is unique, and the bean needs to be consistent with the type of the automatically injected attribute!
4. Annotation supports the implementation process
Import constraints: context constraints
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
Configure annotation support
context:annotation-config/
<?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"> <!--Annotation support--> <context:annotation-config/> <bean id="dog" class="com.kuang.pojo.Dog"/> <bean id="cat" class="com.kuang.pojo.Cat"/> <bean id="people" class="com.kuang.pojo.People"/> </beans>
//required = false description can be null //@Qualifier(value = "dag222") is used with @ Autowired // Corresponding to multiple IDS < bean id = "dog" class = "com. Kuang. POJO. Dog" > < / bean >, you can specify a unique bean injection @Autowired(required = false) @Qualifier(value = "dog222")/*Specify a bean*/ private Dog dog; // @Resources can annotate java with @ Resource without importing configuration // @Resource(name="Dag") specifies the bean id @Resource(name="Cat") private Cat cat;
Use directly on attributes! It can also be used on the set method
If you use the @ Autowired annotation, you can no longer write the set method and implement the underlying reflection, provided that the automatically assembled attribute exists in the IOC container and conforms to the naming specification byName
@Summary of differences between Autowired and @ Resource
- They are all used for automatic assembly, and d can be placed on the attribute field
- @Autowired is implemented by byType, and this object must exist! Commonly used
- @By default, the Resource uses byName. If the name cannot be found, it is implemented by byType. If both cannot be found, an error will be reported
- The execution order is different, @ Autowired defaults to bytype@ Resource is byName by default
4, Using annotation development
Import AOP package org springframework:spring-aop:5.3.7
<?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"> <!--Specify the packages to scan--> <context:component-scan base-package="com.kuang"/> <!--Spring Annotation support--> <context:annotation-config/> </beans>
1.bean
2. How to inject attributes
//@Component is equivalent to < bean id = "user" class = "com. Kuang. Poji. User" / > bean component @Component @Scope("singleton")//Single case public class User { //@Value("Zhang San") is equivalent to < property name = "name" value = "Zhang San" > < / property > annotations can also be placed on the set method @Value("loong") private String name ; @Override //@Scope("prototype") //@Scope("singleton") @Scope("prototype") public String toString() { return "User{" + "name='" + name + '\'' + '}'; } }
3. Derived notes
@Component There are several derived annotations in web During development, it will follow mvc Three tier architecture - dao @Repository - service @Service - controller @Controller These four annotation functions are the same, and they all represent the registration of a class to Spring Middle assembly Bean
4. Automatic installation configuration
- @Autowired Auto assembly pass type,name - @Nullable The field is marked with this annotation, indicating that this field can be null - @Resource Default pass byName If the implementation cannot find the name byType
5. Scope
@Scope("singleton")//Single case @Scope("prototype")//prototype
6. Summary
xml and annotation
- xml is more versatile, suitable for any situation, and easier to maintain
- Annotations are not their own classes. They cannot be used and are relatively complex to maintain
xml and annotation best practices
- xml is used to manage bean s
- Annotations are only responsible for completing dependency injection
- Note that you must enable annotation to take effect and enable annotation support
Dynamic agent
- A dynamic proxy class represents an interface, which generally corresponds to a class of services
- A dynamic proxy class can proxy multiple classes as long as it implements the same interface
5, Configuring Spring in Java
Configuration configuration class
/* This class will also be managed by the spring container and is also a @ Component @Configuration Represents a configuration class similar to beans xml */ @Configuration @ComponentScan("com.kuang") @Import(Kuangconfig2.class) public class Kuangconfig { @Bean public User getUser(){ //The method name is equivalent to the id attribute in beans, and the return value is equivalent to the class attribute return new User(); //Returns the object to be injected into the bean } }
pojo
@Component //This class is taken over by spring and registered in the container public class User { @Value("Bodybuilding") //Injection value private String name;
test
@Test public void test01(){ //If not applicable, ApplicationContext XML configuration using java configuration class requires AnnotationConfig context to obtain Spring container ApplicationContext context = new AnnotationConfigApplicationContext(Kuangconfig.class); User getUser = context.getBean("getUser",User.class);//Method name of configuration class System.out.println(getUser); }
summary
First stage learning