spring(二):IOC配置深入与注解实现
文章目录
一、IoC的CRUD
项目结构:
1.1 导入坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</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.13</version>
<scope>test</scope>
</dependency>
</dependencies>
1.2 创建数据库和实体类
数据库:
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);
实体类:
package domain;
import java.io.Serializable;
/**
* @author konley
* @date 2020-08-17 12:54
* 账户的实体类
*/
public class Account implements Serializable {
private Integer id;
private String name;
private float money;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
}
1.3 持久层接口和实现类
package dao;
import domain.Account;
import java.sql.SQLException;
import java.util.List;
/**
* @author konley
* @date 2020-08-17 13:01
* 账户的持久层接口
*/
public interface IAccountDao {
/**
* description: 查询所有
* @return java.util.List<domain.Account>
*/
List<Account> findAll() throws SQLException;
/**
* description: 查询一个
* @param id
* @return domain.Account
*/
Account findAccountById(Integer id) throws SQLException;
/**
* description: 保存
* @param account
* @return void
*/
void saveAccount(Account account) throws SQLException;
/**
* description: 更新
* @param account
* @return void
*/
void updateAccount(Account account) throws SQLException;
/**
* description: 删除
* @param id
* @return void
*/
void deleteAccount(Integer id) throws SQLException;
}
package dao.impl;
import dao.IAccountDao;
import domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
/**
* @author konley
* @date 2020-08-17 13:03
*/
public class AccountDaoImpl implements IAccountDao {
private QueryRunner runner;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
@Override
public List<Account> findAll() throws SQLException {
return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
}
@Override
public Account findAccountById(Integer id) throws SQLException {
return runner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),id);
}
@Override
public void saveAccount(Account account) throws SQLException {
runner.update("insert into account(name,money) value(?,?) ",account.getName(),account.getMoney());
}
@Override
public void updateAccount(Account account) throws SQLException {
runner.update("update account set name = ?,money = ? where id = ? ",account.getName(),account.getMoney(),account.getId());
}
@Override
public void deleteAccount(Integer id) throws SQLException {
runner.update("delete from account where id = ? ",id);
}
}
1.4 业务层接口和实现类
package service;
import domain.Account;
import java.sql.SQLException;
import java.util.List;
/**
* @author konley
* @date 2020-08-17 12:54
* 账户的业务层接口
*/
public interface IAccountService {
/**
* description: 查询所有
* @return java.util.List<domain.Account>
*/
List<Account> findAll() throws SQLException;
/**
* description: 查询一个
* @param id
* @return domain.Account
*/
Account findAccountById(Integer id) throws SQLException;
/**
* description: 保存
* @param account
* @return void
*/
void saveAccount(Account account) throws SQLException;
/**
* description: 更新
* @param account
* @return void
*/
void updateAccount(Account account) throws SQLException;
/**
* description: 删除
* @param id
* @return void
*/
void deleteAccount(Integer id) throws SQLException;
}
package service.impl;
import dao.IAccountDao;
import domain.Account;
import service.IAccountService;
import java.sql.SQLException;
import java.util.List;
/**
* @author konley
* @date 2020-08-17 12:59
* 业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public List<Account> findAll() throws SQLException {
return accountDao.findAll();
}
@Override
public Account findAccountById(Integer id) throws SQLException {
return accountDao.findAccountById(id);
}
@Override
public void saveAccount(Account account) throws SQLException {
accountDao.saveAccount(account);
}
@Override
public void updateAccount(Account account) throws SQLException {
accountDao.updateAccount(account);
}
@Override
public void deleteAccount(Integer id) throws SQLException {
accountDao.deleteAccount(id);
}
}
1.5 配置文件
<?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">
<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--连接数据库的信息-->
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?useUnicode=true&
characterEncoding=UTF-8&useSSL=false&serverTimezone = GMT"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!--配置QueryRunner-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!--注入数据源-->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!--配置dao-->
<bean id="accountDao" class="dao.impl.AccountDaoImpl">
<!--注入QueryRunner-->
<property name="runner" ref="runner"></property>
</bean>
<!--配置service-->
<bean id="accountService" class="service.impl.AccountServiceImpl">
<!--注入dao-->
<property name="accountDao" ref="accountDao"></property>
</bean>
</beans>
1.6 测试类
import dao.IAccountDao;
import domain.Account;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.sql.SQLException;
import java.util.List;
/**
* @author konley
* @date 2020-08-17 13:21
* 测试xml配置
*/
public class AccountServiceTest {
private ApplicationContext app;
private IAccountDao dao;
@Before
public void getDao(){
app = new ClassPathXmlApplicationContext("beans.xml");
dao = app.getBean("accountDao", IAccountDao.class);
}
@Test
public void findAll() throws SQLException {
List<Account> accounts = dao.findAll();
for (Account account : accounts) {
System.out.println(account);
}
}
@Test
public void findOne() throws SQLException {
Account account = dao.findAccountById(1);
System.out.println(account);
}
@Test
public void save() throws SQLException {
Account account = new Account();
account.setName("ddd");
account.setMoney(2000);
dao.saveAccount(account);
}
@Test
public void update() throws SQLException {
Account account = new Account();
account.setId(4);
account.setName("tony");
account.setMoney(12000);
dao.updateAccount(account);
}
@Test
public void delete() throws SQLException {
dao.deleteAccount(6);
}
}
二、常用注解
1.1 创建bean的注解
和编写一个bean标签实现的功能一致
- @Component:用于把当前类对象存入spring容器中
- value:用于指定bean的id,不写默认是当前类名首字母小写
以下三个注解的作用和@component一样,是spring框架为我们提供明确的三层使用的注解,使三层对象更清晰
- @Controller
- @Service
- @Repository
@Service("accountService")
public class AccountServiceImpl implements IAccountservice {
……
}
1.2 注入数据的注解
和bean标签中写一个property标签的作用一致
(1)注入bean对象的
- @Autowired:自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量类型相匹配,就可以注入
- 出现位置:可以是变量上,也可以出现在方法上
- 细节:在使用注解注入时,不需要set方法也可以注入
- 如果ioc容器中没有任何bean类型和要注入的变量类型一致,报错
- 如果ioc容器中有多个bean类型和要注入的变量类型一致,也报错
@Autowired
private IAccountDao accountDao = null;
- @Qualifier:在按照类中注入的基础上,再按照名称注入。它在给类成员注入时不能单独使用。但是在给方法参数注入时可以
- value:用于指定注入bean的id
- 注意:要和@Autowired一起用
@Qualifier("accountDao2")
private IAccountDao accountDao = null;
- @Resource:直接指定bean的id进行注入,推荐使用
- name:ioc中该bean的id
- 注意:可以独立使用
@Resource(name = "accountDao2")
private IAccountDao accountDao = null;
(2) 注入基本数据类型、String类型的
- @Value:用于注入基本类型和string类型的数据
- value:用于指定数据的值,可以使用spring中的sqEL
- sqEL写法:${表达式}
@Value("1")
private int id;
@Value("xiaoming")
private String name;
(3)集合、复杂类型的注入只能通过xml方式注入
1.3 用于改变作用范围的注解
和bean标签中使用scope属性的作用一致
- @Scope:指定bean的范围
- prototype:多例
- singleton:单例 默认
@Service("accountService")
@Scope("prototype")
public class AccountServiceImpl implements IAccountservice {
……
}
1.4 生命周期相关
和bean标签中使用init-method、destroy-method属性的作用一致
- @PreDestroy:指定销毁方法
- @PostConstruct:指定初始化方法
@PostConstruct
public void init() {
System.out.println("初始化方法");;
}
@PreDestroy
public void destroy() {
System.out.println("销毁方法");
}
三、注解的简单案例
目录结构
3.1 持久层接口和实现类
package dao;
/**
* @author konley
* @date 2020-08-15 20:58
* 账户的持久层接口
*/
public interface IAccountDao {
/**
* description: 模拟保存账户
* @param
* @return void
*/
void saveAccount();
}
package dao.impl;
import dao.IAccountDao;
import org.springframework.stereotype.Repository;
/**
* @author konley
* @date 2020-08-15 21:00
*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Override
public void saveAccount() {
System.out.println("账户保存了");
}
}
3.2 业务层接口和实现类
package service;
/**
* @author konley
* @date 2020-08-15 20:54
* 操作账户业务层接口
*/
public interface IAccountservice {
/**
* description: 模拟保存账户
* @param
* @return void
*/
void saveAccount();
}
package service.impl;
import dao.IAccountDao;
import dao.impl.AccountDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import service.IAccountservice;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.annotation.Resources;
/**
* @author konley
* @date 2020-08-15 20:56
* 账户业务层实现类
*/
//@Component("accountService")
@Service("accountService")
@Scope("prototype")
public class AccountServiceImpl implements IAccountservice {
//@Autowired
//@Qualifier("accountDao")
@Resource(name = "accountDao")
private IAccountDao accountDao = null;
@Override
public void saveAccount() {
accountDao.saveAccount();
}
@PostConstruct
public void init() {
System.out.println("初始化方法");;
}
@PreDestroy
public void destroy() {
System.out.println("销毁方法");
}
}
3.3 xml开启扫描
<?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开启注解扫描的包-->
<context:component-scan base-package="service"></context:component-scan>
<context:component-scan base-package="dao"></context:component-scan>
</beans>
3.4 测试类
package ui;
import dao.IAccountDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.IAccountservice;
import service.impl.AccountServiceImpl;
/**
* @author konley
* @date 2020-08-15 21:10
* 模拟表现层,用于调用业务层(servlet)
*/
public class Client {
public static void main(String[] args) throws Exception {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountservice as = (IAccountservice) ac.getBean("accountService");
System.out.println(as);
as.saveAccount();
}
}
四、配置类注解
-
@Configuration:指定当前是一个配置类
- 当配置类作为AnnotationConfigApplicationContext的参数时,可以不写
-
@ComponentScan:通过注解指定要扫描的包
- value:和basePackage的作用一致,用于指定扫描的包
- 有多个包时使用数组方式传递
-
@Bean:把当前方法的返回值作为bean对象放入ioc容器
- name:用于指定bean的id,默认值是当前方法名
- 如果方法有参数,spring会去容器中查找有没有可用的bean对象
- 查找的方式和AutoWried注解是一样的
-
@Import:用于导入其他的配置类
- value:用于指定其他配置类的字节码,可以是数组
- 当使用import类的注解后,有import注解的类就是父配置类
-
@Properties:用于指定properties文件的位置
- value:指定文件的名称的位置
- 关键字classpath:说明文件在src目录下
五、实现纯注解IoC实现
项目结构
5.1 导入坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</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.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
</dependencies>
5.2 创建数据库和实体类
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);
package domain;
import java.io.Serializable;
/**
* @author konley
* @date 2020-08-17 12:54
* 账户的实体类
*/
public class Account implements Serializable {
private Integer id;
private String name;
private float money;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
}
5.3 持久层接口和实现类
package dao;
import domain.Account;
import java.sql.SQLException;
import java.util.List;
/**
* @author konley
* @date 2020-08-17 13:01
* 账户的持久层接口
*/
public interface IAccountDao {
/**
* description: 查询所有
* @return java.util.List<domain.Account>
*/
List<Account> findAll() throws SQLException;
/**
* description: 查询一个
* @param id
* @return domain.Account
*/
Account findAccountById(Integer id) throws SQLException;
/**
* description: 保存
* @param account
* @return void
*/
void saveAccount(Account account) throws SQLException;
/**
* description: 更新
* @param account
* @return void
*/
void updateAccount(Account account) throws SQLException;
/**
* description: 删除
* @param id
* @return void
*/
void deleteAccount(Integer id) throws SQLException;
}
package dao.impl;
import dao.IAccountDao;
import domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.sql.SQLException;
import java.util.List;
/**
* @author konley
* @date 2020-08-17 13:03
*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
//这里注入了runner
@Autowired
private QueryRunner runner;
@Override
public List<Account> findAll() throws SQLException {
return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
}
@Override
public Account findAccountById(Integer id) throws SQLException {
return runner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),id);
}
@Override
public void saveAccount(Account account) throws SQLException {
runner.update("insert into account(name,money) value(?,?) ",account.getName(),account.getMoney());
}
@Override
public void updateAccount(Account account) throws SQLException {
runner.update("update account set name = ?,money = ? where id = ? ",account.getName(),account.getMoney(),account.getId());
}
@Override
public void deleteAccount(Integer id) throws SQLException {
runner.update("delete from account where id = ? ",id);
}
}
5.4 业务层接口和实现类
package service;
import domain.Account;
import java.sql.SQLException;
import java.util.List;
/**
* @author konley
* @date 2020-08-17 12:54
* 账户的业务层接口
*/
public interface IAccountService {
/**
* description: 查询所有
* @return java.util.List<domain.Account>
*/
List<Account> findAll() throws SQLException;
/**
* description: 查询一个
* @param id
* @return domain.Account
*/
Account findAccountById(Integer id) throws SQLException;
/**
* description: 保存
* @param account
* @return void
*/
void saveAccount(Account account) throws SQLException;
/**
* description: 更新
* @param account
* @return void
*/
void updateAccount(Account account) throws SQLException;
/**
* description: 删除
* @param id
* @return void
*/
void deleteAccount(Integer id) throws SQLException;
}
package service.impl;
import dao.IAccountDao;
import domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.IAccountService;
import java.sql.SQLException;
import java.util.List;
/**
* @author konley
* @date 2020-08-17 12:59
* 业务层实现类
*/
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public List<Account> findAll() throws SQLException {
return accountDao.findAll();
}
@Override
public Account findAccountById(Integer id) throws SQLException {
return accountDao.findAccountById(id);
}
@Override
public void saveAccount(Account account) throws SQLException {
accountDao.saveAccount(account);
}
@Override
public void updateAccount(Account account) throws SQLException {
accountDao.updateAccount(account);
}
@Override
public void deleteAccount(Integer id) throws SQLException {
accountDao.deleteAccount(id);
}
}
5.5 创建主注解配置类
package config;
import org.springframework.context.annotation.*;
//声明当前是一个配置类
@Configuration
//扫描dao和service包的注解
@ComponentScan({"dao","service"})
//导入数据库注解配置类
@Import(JdbcConfig.class)
//导入数据库连接相关的信息
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
}
5.6 创建数据库配置文件
jdbcConfig.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone = GMT
jdbc.username=root
jdbc.password=123456
5.7 创建数据库注解配置子类
package config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;
/**
* @author konley
* @date 2020-08-17 14:33
* 和spring连接数据库相关的配置类
*/
public class JdbcConfig {
/**
*使用Value注入普通类型数据,读取properties在主配置类中完成了
*/
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* description: 创建QueryRunner对象并使用Bean注解将其加载到容器中
* @param dataSource
* @return org.apache.commons.dbutils.QueryRunner
*/
@Bean(name = "runner")
@Scope("prototype")
public QueryRunner createQueryRunner(DataSource dataSource){
return new QueryRunner(dataSource);
}
/**
* description: 创建数据源并使用Bean注解将其加载到容器中
* @param
* @return javax.sql.DataSource
*/
@Bean(name = "dataSource")
public DataSource createDataSource(){
ComboPooledDataSource ds = new ComboPooledDataSource();
try {
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
}catch (Exception e){
e.printStackTrace();
}
return ds;
}
}
5.8 测试类
此时,不再使用ClassPathXmlApplicationContext类通过读取xml来创建容器了
而是使用AnnotationConfigApplicationContext类通过加载主配置类来创建容器
ApplicationContext app = new AnnotationConfigApplicationContext(主配置类.class);
import dao.IAccountDao;
import domain.Account;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.sql.SQLException;
import java.util.List;
/**
* @author konley
* @date 2020-08-17 13:21
* 测试纯注解配置
*/
public class AccountServiceTest {
private ApplicationContext app;
private IAccountDao dao;
@Before
public void getDao(){
//app = new ClassPathXmlApplicationContext("beans.xml");
app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
dao = app.getBean("accountDao", IAccountDao.class);
}
@Test
public void findAll() throws SQLException {
List<Account> accounts = dao.findAll();
for (Account account : accounts) {
System.out.println(account);
}
}
@Test
public void findOne() throws SQLException {
Account account = dao.findAccountById(1);
System.out.println(account);
}
@Test
public void save() throws SQLException {
Account account = new Account();
account.setName("ddd");
account.setMoney(2000);
dao.saveAccount(account);
}
@Test
public void update() throws SQLException {
Account account = new Account();
account.setId(4);
account.setName("tony");
account.setMoney(12000);
dao.updateAccount(account);
}
@Test
public void delete() throws SQLException {
dao.deleteAccount(6);
}
}