文章目录
一. 常用IoC注解
在使用注解配置Spring时,applicationContext.xml配置如下:
告知Spring在创建容器时要扫描的包,配置所需要的标签不在beans中,而是在context名称空间约束中
<?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">
<!--告知Spring在创建容器时要扫描的包,配置所需要的标签不在beans中,而是在context名称空间约束中-->
<context:component-scan base-package="org.iqqcode"/>
</beans>
1. 用于创建对象的
他们的作用就和在XML配置文件中编写一个标签实现的功能是一样的
1. @Component
【出现位置】:类上注解
【作用】:创建当前类对象,并且存入Spring容器中
【属性】:
- value:用于指定bean的id。当我们不写时(属性只有一个),它的默认值是当前类名,且首字母改小写。如果有多个属性值时,必须全部指定出
2. @Controller
- 一般用在表现层
3. @Service
- 一般用在业务层
4. Repository
- 一般用在持久层
以上三个注解他们的作用和属性与Component是一模一样,是对Component的继承。
他们三个是Spring框架为我们提供明确的三层使用的注解,使我们的三层对象更加清晰
2. 用于注入数据的
他们的作用就和在XML配置文件中的bean标签中写一个标签的作用是一样的
1. @Autowired
【出现位置】:可以是变量上,也可以是方法上
【作用】
-
如果IoC容器中有一个类型匹配时,只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
-
如果IoC容器中没有任何bean的类型和要注入的变量类型匹配,则报错。
-
如果IoC容器中有多个类型匹配时:先按照数据类型确定匹配的范围,然后按照变量名称作为唯一
id
,使用@Qualifier
在确定的范围中精确匹配
细节:在使用注解注入时,Setter方法就不是必须的了
2. @Qualifier
【作用】:在按照类中注入的基础之上再按照名称注入。它在给类成员注入时不能单独使用,但是在给方法参数注入时可以直接使用。
【使用】:它在给类成员注入时不能单独使用,必须与@Autowired
配合使用。@Autowired
确定类的匹配范围,@Qualifier
根据变量名精确匹配
【属性】
- value:用于指定注入bean的id
UserDaoImpl
UserServiceImpl为userDao1类注入数据
【在方法上直接使用】
出现多个连接对象时,我们指定连接某一个:
3. @Resource
【作用】:区别于直接按照bean的id注入,它可以独立使用
【 属性】
- name:用于指定bean的id
以上三 个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现。
另外,集合类型的注入只能通过XML来实现。
4. @Value
【作用】:用于注入基本类型和String类型的数据
【属性】:
-
value:用于指定数据的值。它可以使用spring中SpEL(也就是spring的el表达式)
-
SpEL的写法:
${表达式}
3. 用于改变作用范围的
他们的作用就和在bean标签中使用scope
属性实现的功能是一样的
@Scope
【作用】:用于指定bean的作用范围
【属性】
-
value:指定范围的取值,默认是单例的
- 常用取值:singleton(单例),prototype(多例)
- 常用取值:singleton(单例),prototype(多例)
4. 与生命周期相关
他们的作用就和在bean标签中使用init-method
和destroy-methode
的作用是一样的
@PostConstruct
【作用】:用于指定初始化方法
二. Spring与配置相关的注解
通过注解配置类来取代
applicationContext.xml
配置文件
@Configuration
【作用】:指定当前类是一个配置类
【细节】:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。
@ComponentScan
【作用】:用于通过注解指定Spring在创建容器时要扫描的包
【属性】
- value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
我们使用此注解就等同于在xml中配置了:
<context:component-scan base-package="org.iqqcdode"
@Bean
【作用】:用于把当前方法的返回值作为bean对象存入SpringIoC容器中
- name:用于指定bean的id。当不写时,默认值是当前方法的名称
当我们使用注解配置方法时,如果方法有参数, Spring框架会去容器中查找有没有可用的bean对象,查找的方式和Autowired注解的作用是一样的
@Scope
- @Scope(“prototype”),配置多例对象
@Import
当我们有多个配置类时,要将不同的配置类分开写在不同类中。此时,需要有一个主配置类来管理其他子配置类。@Import
注解就相当于把其他配置类(如:JdbcConfig)都导入到主配置类中(SpringConfiguration),只需要加载主配置类,即可加载全部的子配置类。
主配置类:
SpringConfiguration
子配置类:
JdbcConfig
【作用】:用于导入其他的配置类
【属性】
- value:用于指定其他配置类的字节码
当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是配置类.。可以理解为继承关系
@PropertySource
【作用】:用于指定properties文件的位置
【属性】
-
value:指定文件的名称和路径。
-
关键字:classpath,表示类路径下
@PropertySource("classpath:jdbcConfig.properties")
jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_test?characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=1234
该类是一个配置类,它的作用和ApplicationContext.xml是一样的
三. 基于XML连接DBUtils的CRUD
CRUD它又双来了…
对表spring__user进行增删改查
代码都是增删改查的语句很简单,关键是配置信息。
0. Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.iqqcode</groupId>
<artifactId>03_AnnoDemo_CRUD</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>sprin应用程序的入口main方法。 Junit单元测试中,没有main方法也能执行Junit集成了一个main方法,该方法就会判断当前测试类中哪些方法有@Test注解,Junt就让有Test注解的方法执行
Junit不会管我们是否采用 spring框架,在执行测试方法时, Junit根本不知道我们是不是使用了 spring框架,所以也就不会为我们读取配置文件/配置类创建 spring核心容器
由以上三点可知当测试方法执行时,没有Ioc容器,就算写了 Autowired注解,也无法实现注入g-test</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
</dependencies>
</project>
1. 用户实体类User
2. dao层UserDao
UserDao接口
UserDaoImpl
3. service层UserService
UserService接口
UserServiceImpl
4. bean.xml
-
ref属性引入其他bean类
-
采用构造方法注入DBUtils连接池工具类
-
采用Setter注入c3p0连池
<?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">
<!-- 配置Service -->
<bean id="userService" class="org.iqqcode.service.impl.UserServiceImpl">
<!-- 注入dao -->
<property name="userDao" ref="userDao"/>
</bean>
<!--配置Dao对象-->
<bean id="userDao" class="org.iqqcode.dao.impl.UserDaoImpl">
<!-- 注入QueryRunner -->
<property name="run" ref="run"/>
</bean>
<!--配置QueryRunner-->
<bean id="run" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!--注入数据源-->
<constructor-arg name="ds" ref="dataSource"/>
</bean>
<!-- 配置数据源 -->
<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/db_test?characterEncoding=utf-8&useSSL=false"/>
<property name="user" value="root"/>
<property name="password" value="1234"/>
</bean>
</beans>
5. 单元测试类
package org.iqqcode.test;
import org.iqqcode.domain.User;
import org.iqqcode.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
/**
* @Author: Mr.Q
* @Date: 2020-04-30 11:24
* @Description:测试xml--CRUD
*/
public class UserServiceTest {
@Test
public void testFindAll() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
UserService us = ac.getBean("userService", UserService.class);
List<User> users = us.findAll();
for (User user : users) {
System.out.println(user);
}
}
@Test
public void testFindOne() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
UserService us = ac.getBean("userService", UserService.class);
User user = us.findUserById(1);
System.out.println(user);
}
@Test
public void testSava() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
UserService us = ac.getBean("userService", UserService.class);
User user = new User();
user.setName("Java");
user.setAge(22);
us.saveUser(user);
}
@Test
public void testUpdate() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
UserService us = ac.getBean("userService", UserService.class);
User user = us.findUserById(4);
user.setName("Python");
us.updateUser(user);
}
@Test
public void testDelete() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
UserService us = ac.getBean("userService", UserService.class);
us.deleteUser(4);
}
}
四. 基于注解的CRUD
通过注解配置类来取代applicationContext.xml
配置文件
上述代码更改
0. 首先删除applicationContext.xml
创建对象的更改
他们的作用就和在XML配置文件中编写一个<bean>
标签实现的功能是一样的
1. UserDaoImpl
- 添加@Component注解,将实现类对象存入Spring容器
2. UserServiceImpl
与配置相关的注解
创建config包,存放配置类信息
主配置类SpringConfiguration
来管理其他子配置类JdbcConfig
SpringConfiguration
package org.iqqcode.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
/**
* @Author: Mr.Q
* @Date: 2020-04-30 17:12
* @Description:该类是一个配置类,它的作用和bean.xml是一样的
*/
@ComponentScan("org.iqqcode")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration { }
jdbcConfig
package org.iqqcode.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
/**
* @Author: Mr.Q
* @Date: 2020-04-30 17:29
* @Description:和Spring连接数据库相关的配置类
*/
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 创建一个QueryRunner对象
* @param dataSource
* @return
*/
@Bean(name = "run")
@Scope("prototype")
public QueryRunner createQueryRunner(@Qualifier("ds1") DataSource dataSource) {
return new QueryRunner(dataSource);
}
@Bean(name = "ds1")
public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
} catch (PropertyVetoException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
resources下创建 jdbcConfig.properties连接数据库信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_test?characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=root
五. spring-text单元测试
应用程序的入口main方法。 Junit单元测试中,没有main方法也能执行Junit集成了一个main方法,该方法就会判断当前测试类中哪些方法有@Test
注解,Junt就让有Test注解的方法执行
Junit不会管我们是否采用 spring框架,在执行测试方法时, Junit根本不知道我们是不是使用了 spring框架,所以也就不会为我们读取配置文件/配置类创建 spring核心容器
由以上三点可知当测试方法执行时,没有Ioc容器,就算写了 Autowired注解,也无法实现注入
使用spring-test单元测试
Spring整合Junit的配置
-
导入Junti的jar包
-
使用 Junit提供的@RunWith注解把原有的main方法替换成 spring提供的
-
告知 spring的运行器,spring和IoC创建是基于XML还是注解的,并且说明位置
-
@Context Confiquration Locations:指定XML文件的位置,加上 cLasspath关键字,表示在类路径下
-
classes:指定注解类所在地位置
-
当我们使用 spring5.x版本的时候,要求Junit的jar必须是4.12及以上
使用spring-test对上面单元测试的改进
package org.iqqcode.test;
import org.iqqcode.config.SpringConfiguration;
import org.iqqcode.domain.User;
import org.iqqcode.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 java.util.List;
/**
* @Author: Mr.Q
* @Date: 2020-04-30 11:24
* @Description:使用Spring-Junit单元测试
* Spring整合junit的配置
* 1、导入spring整合junit的jar(坐标)
* 2、使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的@Runwith
* 3、告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置
* @ContextConfiguration
* locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
* classes:指定注解类所在地位置
*
* 当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class UserService_SpringTest {
@Autowired
private UserService us = null;
@Test
public void testFindAll() {
List<User> users = us.findAll();
for (User user : users) {
System.out.println(user);
}
}
@Test
public void testFindOne() {
User user = us.findUserById(1);
System.out.println(user);
}
@Test
public void testSava() {
User user = new User();
user.setName("Java");
user.setAge(22);
us.saveUser(user);
}
@Test
public void testUpdate() {
User user = us.findUserById(4);
user.setName("Python");
us.updateUser(user);
}
@Test
public void testDelete() {
us.deleteUser(4);
}
}