Spring02
1. Content introduction
1. Spring Configuration Data Source
2. Spring Annotation Development
3. Spring integrates Junit
Learning objectives
1) Knowing the data source (the role of connection pools)
2) Ability to complete Spring configuration data source
3) Annotation code for spring IOC
4) Ability to write spring and use annotations to scan components
5) Be able to say what spring's IOC annotations mean
6) Can achieve spring integration Junit
2.Spring Configuration Data Source
2.1. The role of data sources (connection pools)
Data sources (connection pools) are used to improve program performance.
Pre-instantiate the data source and initialize part of the connection resources
Get from the data source when using connection resources
Return the connection resource to the data source after use
Common data sources (connection pools):
DBCP, C3P0, BoneCP, Druid, etc.
*** Frequent creation and destruction of connections before is a very server-consuming resource!
Development steps
(1) Importing coordinates of data sources and database-driven coordinates
Creating Data Source Objects
(3) Setting up basic connection data of data source
(4) Accessing and returning connection resources by using data sources
2.2. Manual creation of data sources
2.2.1. Import coordinates
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.32</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.2.RELEASE</version> </dependency> </dependencies>
2.2.2. Create C3P0 Connection Pool
@Test public void testC3P0() throws Exception { //create data source ComboPooledDataSource dataSource = new ComboPooledDataSource(); //Setting database connection parameters dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test"); dataSource.setUser("root"); dataSource.setPassword("root"); //Get the connection object Connection connection = dataSource.getConnection(); System.out.println(connection); }
2.2.3. Create Druid Connection Pool
@Test public void testDruid() throws Exception { //create data source DruidDataSource dataSource = new DruidDataSource(); //Setting database connection parameters dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/test"); dataSource.setUsername("root"); dataSource.setPassword("root"); //Get the connection object Connection connection = dataSource.getConnection(); System.out.println(connection); }
2.2.4. Extract jdbc.properties configuration file
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=root
2.2.5. Read jdbc.properties configuration file to create connection pool
@Test public void testC3P0ByProperties() throws Exception { //jdbc.properties under loading classpath ResourceBundle rb = ResourceBundle.getBundle("jdbc"); ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setDriverClass(rb.getString("jdbc.driver")); dataSource.setJdbcUrl(rb.getString("jdbc.url")); dataSource.setUser(rb.getString("jdbc.username")); dataSource.setPassword(rb.getString("jdbc.password")); Connection connection = dataSource.getConnection(); System.out.println(connection); }
Current problems:
2.3.Spring Configuration Data Source
You can leave the creation of DataSource to the Spring container
* DataSource has parametric constructors, and Spring by default instantiates objects through parametric constructors
* Data Source needs to set up database connection information through set method to use, while Spring can inject string through set method.
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean>
Testing to get data sources from containers
@Test //Test Spring Container to Generate Data Source Objects public void test4() throws Exception { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dataSource = (DataSource) applicationContext.getBean("dataSource"); Connection connection = dataSource.getConnection(); System.out.println(connection); }
** The difference between the two data source configurations:
2.4. Extracting jdbc configuration file
applicationContext.xml loads the jdbc.properties configuration file to obtain connection information.
First, context namespaces and constraint paths need to be introduced:
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--Loading external properties file--> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean>
2.5. Points of knowledge
Spring Integration of Data Source Connection Pool
Spring container loads properties file
3.Spring Annotation Development
Open Annotation Scan
To use annotations, you must add a configuration to applicationContext.xml to turn on annotation scanning
<! - Configure annotation scanning to scan annotations under specified packages - > <context:component-scan base-package="com.itheima"></context:component-scan>
Note: If you want to use annotations, you need to import context namespaces.
Quick Start Code:
3.1.Spring's original annotations
Spring is a framework of light code and reconfiguration, which is heavy to configure and affects the efficiency of development.
So annotation development is a trend. Replacing xml configuration file with annotation can simplify configuration and improve development efficiency.
Spring's original annotations mainly replace the configuration of <Bean>.
Notes
@Component | Use to instantiate beans on classes |
---|---|
@Controller | Use for instantiating beans on web-tier classes |
@Service | Use to instantiate beans on service layer classes |
@Repository | Use for instantiating beans on dao layer classes |
@Autowired | Use on fields for type-dependent injection |
@Qualifier | Used in conjunction with @Autowire for dependency injection by name |
@Resource | Equivalent to @Autowired+@Qualifier, injected by name |
@Value | Injecting common attributes |
@Scope | Scope of action for annotating beans |
@PostConstruct | Using method annotation is the initialization method of Bean |
@PreDestroy | Using method labeling is Bean's destruction method |
1) Classification of original annotations:
1. Used to create objects: the same function as labels in xml configuration - ioc
@Component
@Controller
@Service
@Repository
Function: Make the object of our three-tier architecture clearer, make the development more standardized, conform to the three-tier architecture!
2. Used to inject data: the same as tagging in tags in xml configurations
Note liberation in member variables;
@ Autowired - automatically injects by type; (If there are more than one of the same types, the variable name will be searched)
@ Qualifier - often combined with @Autowired, enhanced @Autowired, injected object name and object mapping, variable name can be arbitrarily selected;
@ Resource -@Resource = Autowired + @Qualifier; note: @Resource requires jdk8
--------------------------------------------------------------------------------------------------------------------------------------------
@ Value - for assigning attributes; - for basic data types + string; and
3. Used to change scope: the same effect as the scope attribute of the tag in the xml configuration
@ Scope - Notes are liberated on classes; single case, multiple cases
4. Life Cycle Relevance (Understanding): The role is the same as that of init-method and destroy-method attributes of tags in xml configuration
@ PostConstruct - Notes are freed in method; executed when initializing objects
@ PreDestroy - Annotations are freed in methods; executed when objects are destroyed
;
3.2. New Annotations to Spring (Current Understanding)
The above annotations can not completely replace the xml configuration file, but also need to use annotations to replace the configuration as follows:
Configuration of non-custom beans:
Loading properties file configuration: context:property-placeholder
Configuration of component scanning: context:component-scan
Introduction of other documents:
annotation | Explain |
---|---|
@Configuration | Used to specify that the current class is a Spring configuration class from which annotations are loaded when a container is created |
@ComponentScan | The package used to specify Spring to scan when initializing the container is the same as the <context:component-scan base-package="com.itheima"/> in Spring's xml configuration file |
@Bean | Using the method, the annotation stores the return value of the method in the Spring container |
@PropertySource | Configuration for loading. properties files |
@Import | For importing other configuration classes |
3.2.1. @Configuration annotation
Effect:
Used to specify that the current class is a spring configuration class from which annotations are loaded when a container is created. You need to use Annotation Application Context (class with @Configuration annotation). It works the same way as bean.xml. When the configuration class is created as a parameter of the AnnotationConfigApplicationContext object, the annotation can be left undone.
That is to specify the current class as a configuration class and pass in as a parameter when creating the container! (instead of applicationContext.xml)
Properties:
value: Byte code for specifying configuration classes
3.2.2. @ComponentScan annotation
Effect:
Used to specify the package spring will scan when initializing the container. The effect is the same as in Spring's xml configuration file: <context: component-scan base-package="com.itheima"/>.
Properties:
basePackages: Used to specify the package to scan. The value attribute in this annotation works the same way.
@ ComponentScan("com.itheima") or @ComponentScan (base Packages = com.itheima)
Equivalent to substitution:
3.2.3. @Bean annotation
@ Bean: Used to store the return value of the current method as a bean object in spring's ioc container, and its name attribute is used to specify the id of the bean. When not written, the default value is the name of the current method
@ What's the difference between a bean and @component?
@ bean Annotation - Write in the method, the return value of the method is stored in the spring container;
@ component - Write on the class, create objects for the current class, and store them in the spring container!
3.2.4. @Import annotation
@ Import is used to import other configuration classes
3.2.5. @PropertySource annotation (understand)
Effect:
@ PropertySource is used to load the configuration in the. properties file. For example, when we configure a data source, we can write information about connecting to the database to the properties configuration file, and we can use this annotation to specify the location of the properties configuration file.
Properties:
value []: Used to specify the location of the properties file. If it's in the classpath, you need to write the classpath
** Configuration of spring development:
1. Pure xml: - bean Management + data injection + data source configuration; all need to write configuration files, as the project advances, dao/service configuration will become more and more;
2. Semi-Annotation + Semi-xml:- Data source uses xml; bean management is handed over to annotation, data injection is handed over to annotation; the simplest way
3. Pure annotation: - Although there is no xml, the code that programmers need to write actually becomes more and more, writing more configuration classes!
4.Spring Integrates Junit (Understanding)
4.1. Problems with the original Junit test Spring
In the test class, each test method has the following two lines of code:
The purpose of these two lines of code is to get the container and, if not written, prompt null pointer exceptions directly. So it can't be easily deleted.
4.2. Solutions to the above problems
Let Spring Junit be responsible for creating Spring containers, but you need to tell it the name of the configuration file
Test beans will need to be injected directly into test classes
4.3.Spring integration Junit step
1. Import spring to integrate Junit coordinates
(2) Replace the original run time with the @Runwith annotation
(3) Use @ContextConfiguration to specify configuration files or classes
(4) Injecting objects to be tested with @Autowire
(5) Create test methods for testing
4.4.Spring Integrated Junit Code Implementation
1. Import spring to integrate Junit coordinates
<!--It should be noted here that: spring5 Version requirements above junit The version must be 4.12 And above--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
(2) Replace the original run time with the @Runwith annotation
* attention:
-
If annotation configuration is used, @ContextConfiguration should specify the bytecode of the configuration class -- full annotation
@ContextConfiguration(classes = SpringConfig.class) -
If a configuration file is used, @ContextConfiguration should specify the location xml of the configuration file
@ContextConfiguration(locations = "classpath:beans.xml")
* When using spring 5.x, it is required that junit's jar be 4.12 or more (it is recommended that junit's 4.12 match spring's 5.0.x).