Common dependency
1. Pring context dependency
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.13</version> </dependency>
3.junit
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
4. Database driven
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.32</version> </dependency>
5.druid data pool
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency>
6.spring-test
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.3.13</version> </dependency>
1. Introduction to spring
1.Bean tag configuration and instantiation
<bean id="" class="" scope="" init-method="" destroy-method=""></bean>
1. Basic configuration:
By default, Bean calls the parameterless constructor in the class. If there is no parameterless constructor, it cannot be created successfully.
Basic properties:
id: the unique identifier of the Bean instance in the Spring container
Class: the fully qualified name of the bean, that is, the full package name. You can copy the Reference of the referenced class
2. Scope configuration:
Scope: refers to the scope of the object. The values are as follows:
Value range | explain |
---|---|
singleton | Default, singleton |
prototype | Multiple cases |
request | In the WEB project, Spring creates a Bean object and stores the object in the request field |
session | In the WEB project, Spring creates a Bean object and stores the object into the session domain |
global session | In the WEB project, the application is in the Portlet environment. If there is no Portlet environment, the globalSession is equivalent |
2.1. When the value of scope is singleton
Number of instantiations of Bean: 1
Bean instantiation timing: instantiate the configured bean instance when the Spring core file is loaded
Bean life cycle:
Object creation: when the application loads and creates a container, the object is created
Object running: the object remains alive as long as the container is
Object destruction: when the application unloads and destroys the container, the object is destroyed
2.2. When the value of scope is prototype
Number of Bean instantiations: multiple
Instantiation timing of Bean: instantiate Bean when calling getBean method
Object creation: creates a new object instance when using an object
Object running: as long as the object is in use, it will always be alive
Object destruction: when an object is not used for a long time, it is recycled by the Java garbage collector
3. Life cycle configuration (unimportant)
Init method: Specifies the name of the initialization method in the class
Destroy method: Specifies the name of the destroy method in the class
4. Three methods of bean instantiation
1. Instantiation focus of parameterless construction method
<bean id="userDao" class="com.home.dao.impl.UserDaoImpl"></bean>
2. Factory static method instantiation
Because it is static, you can directly call the methods in the static
public class StaticFactory { public static UserDao getUserDao(){ return new UserDaoImpl(); } }
<bean id="userDao" class="com.home.factory.StaticFactory" factory-method="getUserDao"></bean>
3. Factory instance method instantiation
If it is dynamic, there must be a factory object before calling its methods
public class DynamicFactory { public UserDao getUserDao(){ return new UserDaoImpl(); } }
<bean id="factory" class="com.home.factory.DynamicFactory"></bean> <bean id="userDao" factory-bean="factory" factory-method="getUserDao"></bean>
2. Dependency injection of bean
Dependency injection: it is the concrete implementation of the Spring framework core IOC.
Use Spring to maintain the dependencies between the business layer and the persistence layer. Simply put, it means waiting for the framework to transfer the persistence layer object to the business layer without getting it ourselves.
1. Injection method
1.1 construction method
By generating parametric structure and nonparametric structure
private UserDao userDao; public UserServiceImpl(UserDao userDao) { this.userDao = userDao; } public UserServiceImpl() { }
<bean id="userDao" class="com.home.dao.impl.UserDaoImpl"></bean> <bean id="userService" class="com.home.service.Impl.UserServiceImpl"> <constructor-arg name="userDao" ref="userDao"></constructor-arg> </bean>
The name value in the constructor Arg tag is derived from the parameters in the parameterized constructor
1.2set method (multi use)
private UserDao userDao; public void setUserDao(UserDao userDao) { this.userDao = userDao; } public void save(){ userDao.save(); }
<bean id="userDao" class="com.home.dao.impl.UserDaoImpl"></bean> <bean id="userService" class="com.home.service.Impl.UserServiceImpl"> <property name="userDao" ref="userDao"></property> </bean>
The name value in property comes from userDao in the setUserDao method name
2. Set type injection
<bean id="userDao" class="com.home.dao.impl.UserDaoImpl"> <!--List type--> <property name="strList"> <list> <value>123</value> <!--Common type use<value>--> <ref>User</ref> <!--Object use<ref>--> </list> </property> <!--map type--> <property name="userMap"> <map> <entry key="user1" value-ref="user"></entry> </map> </property> <!--properties type--> <property name="properties"> <props> <prop key="p1">123</prop> <prop key="p1">456</prop> </props> </property> </bean>
3. Import other configuration files
<import resource="Files to import"></import>
3. Configure druid in spring
1.pom. Importing MySQL connector Java and druid dependencies into XML
2. Create a new ApplicationContext in the Resources folder XML and JDBC Properties file
3.jdbc. Configure database information in the properties file
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=root
4. In ApplicationContext Configuration in XML file
<?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"> <!--Load external properties file--> <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>
5. Test class
public void test3() throws Exception{ ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dataSource = (DataSource) app.getBean("dataSource"); Connection connection = dataSource.getConnection(); System.out.println(connection); connection.close(); }
2.Spring annotation development
1.Spring original annotation
Spring's original annotations are mainly used to replace the configuration of Bean tags
annotation | explain |
---|---|
@Component | Used on classes to instantiate beans |
@Controller | Used on web tier classes to instantiate beans |
@Service | Used on the service layer class to instantiate beans |
@Repository | Used on dao layer classes to instantiate beans |
@Autowired | Use on field for type dependent injection |
@Qualifier | Used in conjunction with @ Autowired for dependency injection by name |
@Resource | Equivalent to @ Autowired+@Qualifier, injected by name |
@Value | Inject common attributes |
@Scope | Label the scope of the Bean |
@PostConstruct | Use to label the method, which is the initialization method of Bean |
@PreDestroy | Use to mark the method as the destruction method of Bean |
/*<bean id="userService" class="com.home.service.impl.UserServiceImpl"></bean> Equivalent to */ @Component("userService") /*<property name="userDao" ref="userDao"></property> Equivalent to*/ @Autowired /*Matching from the Spring container according to the data type can be used separately, but this method fails when there are multiple same data types in the container*/ @Qualifier("userDao") /*Match from the container according to the ID, which should be used together with @ Autowired*/ /*Or directly @ Resource(name="userDao") is equivalent to @ Autowired + @Qualifier*/
Note: in ApplicationContext XML ` ` to configure component scanning
<context:component-scan base-package="com.home" />
When annotation is used, the set method may not be written
When using xml, the set method needs to write
General type notes:
@Value("${jdbc.driver}") private String driver;
But in ApplicationContext In the XML file, to load the external properties file:
<context:property-placeholder location="classpath:jdbc.properties" />
2. New annotation of spring*
annotation | explain |
---|---|
@Configuration | Used to specify that the current class is a Spring configuration class, and annotations will be loaded from this class when the container is created |
@ComponentScan | Used to specify the package that Spring will scan when initializing the container. The function is the same as the < context: component scan base package = "com. Home" / > in the xml configuration file of Spring |
@Bean | On a method, the annotation stores the return value of the method in the Spring container |
@PropertySource | For loading Configuration in the properties file |
@lmport | Used to import other configuration classes |
With the new annotation, you can configure without XML at all
1. Contents
2.SpringConfiguration and DataSourceConfiguration files
package com.home.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; //This class is the core configuration class of Spring @Configuration //<context:component-scan base-package="com.home" /> @ComponentScan("com.home") //<import resource=""/> @Import({DataSourceConfiguration.class}) public class SpringConfiguration { }
package com.home.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import javax.sql.DataSource; //<context:property-placeholder location="classpath:jdbc.properties" /> @PropertySource("classpath:jdbc.properties") public class DataSourceConfiguration { @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") //Spring will store the return value of the current method in the spring container with the specified name public DataSource getDataSource(){ DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(driver); druidDataSource.setUrl(url); druidDataSource.setUsername(username); druidDataSource.setPassword(password); return druidDataSource; } }
3. In the test category
public class Start { @Test public void test1(){ ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class); UserService userService = (UserService) app.getBean("userService"); userService.save(); } }
3.Spring integration Junit
1. Import spring test and junit dependencies
2. In the test category
package com.home.test; import com.home.config.SpringConfiguration; import com.home.service.UserService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.sql.DataSource; import java.sql.SQLException; @RunWith(SpringJUnit4ClassRunner.class) //@ContextConfiguration("classpath:applicationContext.xml") @ContextConfiguration(classes = {SpringConfiguration.class}) public class SpringJunit { @Autowired private UserService userService; @Autowired private DataSource dataSource; @Test public void test1() throws SQLException { userService.save(); System.out.println(dataSource.getConnection()); } } on; @RunWith(SpringJUnit4ClassRunner.class) //@ContextConfiguration("classpath:applicationContext.xml") @ContextConfiguration(classes = {SpringConfiguration.class}) public class SpringJunit { @Autowired private UserService userService; @Autowired private DataSource dataSource; @Test public void test1() throws SQLException { userService.save(); System.out.println(dataSource.getConnection()); } }