1.Spring’s two cores

Two cores:

Inverse Of Control

AOP (Aspect Oriented Programming).

IOC is not a technology, but a design idea. Its purpose is to guide us to design programs that are more loosely coupled.

Control: In Java, control over objects (create, destroy)

Reversal: Refers to the reversal of object control from manual control by the developer in the class to control by the Spring container

2. Spring related API

2.1 the BeanFactory

The BeanFactory is the core interface of the IOC container, which defines the basic functions of IOC.

Features: The first time the getBean() method is called, an instance of the specified object is created

2.2 ApplicationContext

Apply the context object to get the Bean object of the IOC container in Spring.

Features: When the Spring container starts, instances of all objects are loaded and created

2.3 BeanFactory differs from ApplicationContext

  • BeanFactory is the top interface of the IoC container in the Spring framework. It is used to define basic functions and specifications. ApplicationContext is one of its subinterfaces. So the ApplicationContext has all the functionality provided by the BeanFactory.

  • Generally, we call the BeanFactory the base container of SpringIOC, and the ApplicationContext is the high-level interface of the container that has more functionality than the BeanFactory, such as internationalization support and resource access (XML, Java configuration classes) and so on

  • When the ApplicationContext is loaded, the bean object is created and stored in the container

  • The BeanFactory does not create a bean object to store in the container until it is loaded into the IOC container when the getBean method is called

/** * @author * @date 2021/06/17 21:11 */ public class SpringTest {@test public void test1() { The up and down objects can be used to obtain bean objects in the IOC container, The bean object is created and stored in the container. ApplicationContext ApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); / / use the context object from the IOC container to bean object IUserDao userDao = (IUserDao) applicationContext. GetBean (" userDao "); userDao.save(); } @test public void test2() {//BeanFactory the core interface does not create bean objects to store in the container BeanFactory BeanFactory = new XmlBeanFactory(new) ClassPathResource("applicationContext.xml")); IUserDao userDao = (IUserDao) beanFactory.getBean("userDao"); userDao.save(); }}Copy the code

3. Spring configuration file

3.1 What is a bean

In Spring, the objects that make up the backbone of an application and are managed by the Spring IoC container are called beans. A bean is an object instantiated, assembled, and managed by the Spring IoC container.

3.2 Basic Configuration of Bean Labels

<bean id="" class="" scope=""  init-method="" destroy-method="" ></bean>
Copy the code
  • By default, it calls the no-argument constructor of the class, and can’t be created without it.
  • Id: Unique identification of the Bean instance in the Spring container
  • Class: Fully qualified name of the Bean
  • The scope attribute refers to the scope of the object
    • Singleton default value, singleton
    • More than the prototype
  • Init-method: Specifies the name of the initialization method in the class
  • Destroy-method: specifies the name of the destroy-method in the class

3.2.1 When the value of scope is singleton

Bean life cycle: Object creation: When the application is loaded, the object is created when the container is created. The object runs: As long as the container is present, the object is alive. Object destruction: When the application is uninstalled and the container is destroyed, the object is destroyedCopy the code

3.2.2 When scope is set to Prototype

The Bean life cycle: Object creation: When an object is used, a new instance of an object is created. The object runs: As long as the object is in use, it is alive. Object destruction: When objects are not used for a long time, they are collected by the Java garbage collectorCopy the code

3.3 There are three ways to instantiate beans

3.3.1 Instantiation of the no-parameter constructor

It creates the class object based on the default no-argument constructor, which will fail if there is no default no-argument constructor in the bean

<? The 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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <! One - way: a no-parameter constructor instantiated -- > < bean id = "userDao" class = "com. Lagou. Dao. Impl. UserDaoImpl" > < / bean > < / beans >Copy the code

3.3.2 Factory static method instantiation

Application scenarios

Class A has A static method m1 whose return value is A B object. If we use B objects frequently, we can hand over the creation of B objects to Spring’s IOC container, so that we can use B objects directly from the IOC container in the future without calling the M1 method of class A.

<! -- Method 2: Static factory methods to instantiate - > < bean id = "userDao" class = "com. Lagou. Factory. StaticFactoryBean" factory - method = "createUserDao" > < / bean >Copy the code
package com.lagou.factory; import com.lagou.dao.IUserDao; import com.lagou.dao.impl.UserDaoImpl; /** * @author * @date StaticFactoryBean {public StaticFactoryBean {public StaticFactoryBean () { return new UserDaoImpl(); }}Copy the code

3.3.3 Instantiation of factory common methods

Application scenarios

Class A has A common method m1, whose return value is A B object. If we use B objects frequently, we can hand over the creation of B objects to Spring’s IOC container, so that we can use B objects directly from the IOC container in the future without calling the M1 method of class A.

<! -- Method 3: Factory ordinary methods to instantiate - > < bean id = "dynamicFactoryBean" class = "com. Lagou. Factory. DynamicFactoryBean" > < / bean > < bean id = "userDao" factory-bean="dynamicFactoryBean" factory-method="createUserDao"></bean>Copy the code
package com.lagou.factory; import com.lagou.dao.IUserDao; import com.lagou.dao.impl.UserDaoImpl; /** * @author * @date 2021/06/17 23:07 */ public DynamicFactoryBean {public IUserDao createUserDao() {return new UserDaoImpl(); }}Copy the code

3.4 Dependency injection method for beans

Dependency Injection DI (DI) : It is a concrete implementation of IOC, the core of the Spring framework.

When you write your program, you leave the creation of the object to Spring through inversion of control, but you can’t have code that doesn’t have dependencies. IOC decoupling only reduces their dependencies, but does not eliminate them.

For example, the business layer still calls the methods of the persistence layer. The dependency between the business layer and the persistence layer will be maintained by Spring after Spring is used. To put it simply, the persistence layer object is passed to the business layer through the framework without having to fetch it ourselves.

3.4.1 Maintain the dependency between the service layer and the persistence layer

(1)UserServiceImpl.java

/** * @author * @date 2021/06/17 23:26 */ public class UserServiceImpl implements UserService {@override public void Save () {/ / call the method that userDao ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); IUserDao userDao = (IUserDao) applicationContext.getBean("userDao"); userDao.save(); }}Copy the code

(2) applicationContext.xml

<! - configuration UserService - > < bean id = "useService" class = "com. Lagou. Service. Impl. UserServiceImpl" > < / bean >Copy the code

(3) Test.java

@test public void Test () {// Get the spring context object. The bean object is created and stored in the container. ApplicationContext ApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); / / use the context object from the IOC container to bean object UserService UserService = (UserService) applicationContext. GetBean (" useService "); userService.save(); }Copy the code

3.4.2 Constructor injection

(1) UserServiceImpl.java

public class UserServiceImpl implements UserService { private IUserDao userDao; public UserServiceImpl(IUserDao userDao){ this.userDao = userDao; } @Override public void save() { userDao.save(); }}Copy the code

(2) applicationContext.xml

Index Indicates the subscript position of the constructor parameter

Type Constructor parameter type

The bean that ref depends on

<! UserDao - configuration - > < bean id = "UserDao" class = "com. Lagou. Dao. Impl. UserDaoImpl" > < / bean > <! - configuration UserService - > < bean id = "useService" class = "com. Lagou. Service. Impl. UserServiceImpl" > < constructor - arg index = "0" type="com.lagou.dao.IUserDao" ref="userDao" /> </bean>Copy the code

The name parameter name can be simplified

<! UserDao - configuration - > < bean id = "UserDao" class = "com. Lagou. Dao. Impl. UserDaoImpl" > < / bean > <! - configuration UserService - > < bean id = "useService" class = "com. Lagou. Service. Impl. UserServiceImpl" > < constructor - arg name="userDao" ref="userDao" /> </bean>Copy the code

3.4.3 Set method injection

(1) UserServiceImpl.java

public class UserServiceImpl implements UserService { private IUserDao userDao; public void setUserDao(IUserDao userDao) { this.userDao = userDao; } @Override public void save() { userDao.save(); }}Copy the code

(2) applicationContext.xml

The first letter of the UserDao after the name set method setUserDao is lowercase

The bean that ref depends on

<! UserDao - configuration - > < bean id = "UserDao" class = "com. Lagou. Dao. Impl. UserDaoImpl" > < / bean > <! - configuration UserService - > < bean id = "useService" class = "com. Lagou. Service. Impl. UserServiceImpl" > < property name = "userDao" ref="userDao" /> </bean>Copy the code

3.4.4P namespace injection

P namespace injection is also set injection, but it is more convenient than the above set injection, which is mainly reflected in the configuration file as follows:

First, we need to introduce the P namespace:

xmlns:p="http://www.springframework.org/schema/p"
Copy the code

Second, you need to modify the injection mode:

<bean id="userDao" class="com.lagou.dao.impl.UserDaoImpl"/>
<bean id="userService" class="com.lagou.service.impl.UserServiceImpl" p:userDao-ref="userDao"/>
Copy the code

3.5 Bean injection of common data types

3.5.1 Common Data Types

package com.lagou.domain; /** * @author * @date 2021/06/18 21:07 */ public class User {private String username; private String age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getAge() { return age; } public void setAge(String age) { this.age = age; }}Copy the code

Value is used for injection of common data types

Ref is used for injection of reference data types

 <bean id="user" class="com.lagou.domain.User">
    <property name="username" value="yangzhen" />
    <property name="age" value="20" />
</bean>
Copy the code

3.5.2 Reference Data Types

Same as set method above for injection

3.5.3 Set data types

(1) list/set/Array

Replace the label.

/** * @author * @date 2021/06/18 21:21 */ public class UserGroup {private String groupName; List<Object> userList; public void setGroupName(String groupName) { this.groupName = groupName; } public void setUserList(List<Object> userList) { this.userList = userList; }}Copy the code
<bean id="user" class="com.lagou.domain.User"> <property name="username" value="yangzhen" /> <property name="age" value="20" /> </bean> <bean id="userGroup" class="com.lagou.domain.UserGroup"> <! <property name="groupName" value="TFboys" /> <! <property name="userList"> < List > <! Yang1 </value> <! Yang1 </value> <! </ref> </list> </property> </bean>Copy the code

(2) Map

/** * @author * @date 2021/06/18 21:21 */ public class UserGroup {private String groupName; List<Object> userList; private Map<String,Object> map; public void setMap(Map<String, Object> map) { this.map = map; } public void setGroupName(String groupName) { this.groupName = groupName; } public void setUserList(List<Object> userList) { this.userList = userList; } public Map<String, Object> getMap() { return map; }}Copy the code
<bean id="user" class="com.lagou.domain.User"> <property name="username" value="yangzhen" /> <property name="age" value="20" /> </bean> <bean id="userGroup" class="com.lagou.domain.UserGroup"> <! <property name="groupName" value="TFboys" /> <! Yang1 </value> <ref bean="user"></ref> </ List >yang1</value> <ref bean="user"></ref> </ List > </property> <! <property name=" Map "> < Map > <! - ordinary type use value - > < entry key = "k1" value = "k1Value" > < / entry > <! - reference types use value - ref - > < entry key = "k2" value - ref = "user" > < / entry > < / map > < / property > < / bean >Copy the code

(3) Properties

public class UserGroup { private Properties properties; public void setProperties(Properties properties) { this.properties = properties; } public Properties getProperties() { return properties; }}Copy the code
<bean id="userGroup" class="com.lagou.domain.UserGroup"> <! <property name="groupName" value="TFboys" /> <! Yang1 </value> <ref bean="user"></ref> </ List >yang1</value> <ref bean="user"></ref> </ List > </property> <! <property name=" Map "> < Map > <! - ordinary type use value - > < entry key = "k1" value = "k1Value" > < / entry > <! -- value-ref--> <entry key="k2" value-ref="user"></entry> </map> </property> <property name="properties"> <props> <prop key="k1">v1</prop> <prop key="k2">v2</prop> </props> </property> </bean>Copy the code

3.6 Modularization of configuration Files

Configuration file modularization: Decomposes some configurations to other configuration files

3.6.1 Parallel configuration files

ApplicationContext act = new ClassPathXmlApplicationContext("beans1.xml","beans2.xml","..." );Copy the code

3.6.2 Parallel configuration files

<import resource="applicationContext-xxx.xml"/>
Copy the code

Note:

  • Beans with the same name cannot appear in the same XML; if they do, an error will be reported.
  • Multiple XML files with beans of the same name will not report an error, but the loaded bean will overwrite the loaded bean

3.6.3 Extracting the JDBC configuration file

Applicationcontext.xml loads the jdbc.properties configuration file for connection information.

The context namespace and constraint path need to be introduced

<? The 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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property  name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> </beans>Copy the code

4. Spring annotation development

4.1 Common Comments

Spring common annotations are mainly alternative configurations

annotations instructions
@Component Used to instantiate beans on a class
@Controller Used to instantiate beans on web layer classes
@Service Used to instantiate beans on service layer classes
@Repository Used to instantiate beans on dao layer classes
@Autowired Used on fields for dependency injection by type
@Qualifier Used in conjunction with @autowired, dependency injection by name
@Resource Equivalent to @autowired +@Qualifier, injected by name
@Value Injecting common properties
@Scope The scope of the annotation Bean
@PostConstruct Use the annotation on a method that is the Bean’s initialization method
@PreDestroy Use the annotation on the method that the method is the Bean’s destruction method

Description:

The @Resource annotation cannot be used because javax extensions have been completely removed in JDK11

Maven is required to introduce dependencies

< < the dependency > < groupId > javax.mail. An annotation/groupId > < artifactId > javax.mail. The annotation - API < / artifactId > < version > 1.3.2 < / version > </dependency>Copy the code

Pay attention to

When developing with annotations, you configure component scanning in applicationContext.xml to specify which package and beans under its subpackages need to be scanned to identify classes, fields, and methods configured with annotations.

<! <context:component-scan base-package="com.lagou"></context:component-scan>Copy the code

The sample

@service @scope ("singleton") public class UserServiceImpl implements UserService {@Value(" implements Ordinary Data ") private String STR; @Value("${jdbc.driver}") private String driver; @Autowired private UserDao userDao; @construct public void init(){system.out.println (" init method...." ); } @destroy public void destroy(){system.out.println (" destroy method.....") ); }}Copy the code

4.2 Spring new notes

Not all XML configuration files can be replaced with the above annotations, but the following configurations need to be replaced with annotations:

  • Configuration of non-custom beans:
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${jdbc.driver}"></property>
    <property name="url" value="${jdbc.url}"></property>
    <property name="username" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>
</bean>
Copy the code
  • Loading the properties file configuration:
<context:property-placeholder location="classpath:jdbc.properties"/>
Copy the code
  • Configuration of component scanning:
<! <context:component-scan base-package="com.lagou"></context:component-scan>Copy the code
  • Import other files:
<import resource="applicationContext-xxx.xml"/>
Copy the code
annotations instructions
@Configuration Used to specify that the current class is a Spring configuration class from which annotations will be loaded when the container is created
@Bean With a method, the annotation stores the return value of that method in the Spring container
@PropertySource Used to load the configuration in the properties file
@ComponentScan Used to specify the packages to be scanned by Spring when the container is initialized
@Import Used to import other configuration classes

4.2.1 Writing Spring core configuration classes

@Configuration @ComponentScan("com.lagou") @Import(DataSourceConfig.class) public class SpringConfig { @Bean("queryRunner") public QueryRunner getQueryRunner(@Autowired DataSource dataSource) { return new QueryRunner(dataSource); }}Copy the code

4.2.2 Compiling database configuration Information classes

@PropertySource("classpath:jdbc.properties") public class DataSourceConfig { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean("dataSource") public DataSource getDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; }}Copy the code

5. Junit Spring integration

5.1 Common Junit testing problems

In a normal test class, the developer manually loads the configuration file and creates the Spring container, then obtains the Bean instance through the Spring-related API.

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

AccountService accountService = applicationContext.getBean(AccountService.class);

Copy the code

5.2Spring integrates Junit steps

    1. Import spring integration Junit coordinates
    1. Replace the original runner with the @runwith annotation
    1. Use @contextConfiguration to specify a configuration file or configuration class
    1. Inject objects to be tested using @AutoWired
    1. Create test methods to test
<! -- It is important to note here that <dependency> <groupId>org.springframework</groupId> junit must be 4.12 or later. < artifactId > spring - test < / artifactId > < version > 5.1.5. RELEASE < / version > < / dependency > < the dependency > <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>Copy the code
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {SpringConfig.class}) public class SpringJunitTest { @Autowired private AccountService accountService; @test public void testFindById() {Account Account = AccountService.findById (3); @test public void testFindById() {Account Account = AccountService.findById (3); System.out.println(account); }}Copy the code