Spring-ioc
按照下列格式创建包和类
创建UserController类
package controller;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import services.UserService;
import services.impl.UserServiceImpl;
import vo.UserVo;
@Controller
public class UserController {
/*
引入IOC之前
private UserService userService;
public UserVo getVo(Integer id) {
// 手动实例化Service
userService = new UserServiceImpl();
// 执行Service层方法并返回
return userService.getVo(id);
}*/
private UserService userService;
public UserVo getVo(Integer id, ApplicationContext context) {
// 从Spring容器拿Service
userService = (UserService) context.getBean("userService");
// 执行Service层方法,因为之后还需要用到context对象,故下传
return userService.getVo(id, context);
}
}
创建UserDao接口类
package dao;
import entity.User;
public interface UserDao {
User getEntity(Integer id);
}
创建UserDaoImpl类
package dao.impl;
import dao.UserDao;
import entity.User;
import org.springframework.stereotype.Repository;
@Repository("userDao")
public class UserDaoImpl implements UserDao {
public User getEntity(Integer id) {
// 此处应该从数据库查询值 方便起见直接返回一个固定对象
User user = new User();
user.setId(1);
user.setName("Anne");
user.setGender(0);
return user;
}
}
创建User类
package entity;
public class User {
private Integer id;
private String name;
private Integer gender;
// getter&setter方法
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 Integer getGender(){
return gender;
}
public void setGender(Integer gender){
this.gender=gender;
}
}
当中getter&setter方法是自动生成的,快捷键为“Alt+Insert”按完之后出现下列图片
然后选择Getter and Seter,全选然后点击OK
创建UserService接口类
package services;
import org.springframework.context.ApplicationContext;
import vo.UserVo;
public interface UserService {
UserVo getVo(Integer id);
UserVo getVo(Integer id, ApplicationContext context);
}
创建UserServiceImpl类
package services.impl;
import dao.UserDao;
import dao.impl.UserDaoImpl;
import entity.User;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import services.UserService;
import vo.UserVo;
@Service("userService")
public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserVo getVo(Integer id, ApplicationContext context) {
// 从Spring容器拿Dao
userDao = (UserDao) context.getBean("userDao");
// 执行Dao层方法
User user = userDao.getEntity(id);
// 省略业务逻辑处理。。。
UserVo userVo = new UserVo(user);
userVo.setGenderName(userVo.getGender() == 0 ? "female" : "male");
return userVo;
}
public UserVo getVo(Integer id) {
return null;
}
}
创建UserVo类
package vo;
import entity.User;
public class UserVo {
private Integer id;
private String name;
private Integer gender;
private String genderName;
// getter&setter方法
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 Integer getGender(){
return gender;
}
public void setGender(Integer gender){
this.gender=gender;
}
public UserVo() {
}
public UserVo(User user) {
this.id = user.getId();
this.name = user.getName();
this.gender = user.getGender();
}
// toString方法
public String toString(){
return "User{"+
"id="+id+
",name='"+name+'\''+
",genderName="+genderName+
",gender="+gender+'}';
}
public void setGenderName(String genderName) {
this.genderName = genderName;
}
}
同样的toString方法也是和上面的getter&setter方法一样是自动生成的,用的都是快捷键生成的。
配置资源文件applicationContest.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:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
https://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
">
<!-- bean definitions here -->
<context:component-scan base-package="dao"/>
<context:component-scan base-package="services"/>
<context:component-scan base-package="controller"/>
</beans>
创建UserTest测试类
import controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import vo.UserVo;
public class UserTest {
public static void main(String[] args) {
// 读取配置文件刷新Spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
// 从Spring容器拿Controller
UserController userController = (UserController) context.getBean("userController");
// 执行Controller层方法,因为之后还需要用到context对象,故下传
UserVo userVo = userController.getVo(1, context);
System.out.println(userVo);
}
}
运行UserTest测试类
简单的实现Spring-aop
按照下列格式创建包和类
准备好数据
# 使用spring_aop数据库
use spring_aop;
# 创建account表
create table account (
id int(11) auto_increment primary key,
accountNum varchar(20) default NULL,
money int(8) default 0
);
# 新增数据
insert into account (accountNum, money) values
("622200001",1000),("622200002",1000);
创建AccounDao接口类
package dao;
import entity.Account;
public interface AccountDao {
/**
* 更新
*
* @param account
*/
void updateAccount(Account account);
/**
* 根据编号查询账户
*
* @param accountNum
* @return 如果没有结果就返回null,如果结果集超过一个就抛异常,如果有唯一的一个结果就返回
*/
Account findAccountByNum(String accountNum);
}
创建AccounDaoImpl类
package dao.impl;
import dao.AccountDao;
import entity.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import utils.ConnectionUtils;
import java.sql.SQLException;
import java.util.List;
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
// 数据库查询工具类
@Autowired
private QueryRunner runner;
// 数据库连接工具类
@Autowired
private ConnectionUtils connectionUtils;
/**
* 更新
*
* @param account
*/
public void updateAccount(Account account) {
try {
runner.update(connectionUtils.getThreadConnection(),
"update account set accountNum=?,money=? where id=?",
account.getAccountNum(), account.getMoney(), account.getId());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 根据编号查询账户
*
* @param accountNum
* @return 如果没有结果就返回null,如果结果集超过一个就抛异常,如果有唯一的一个结果就返回
*/
public Account findAccountByNum(String accountNum) {
List<Account> accounts = null;
try {
accounts = runner.query(connectionUtils.getThreadConnection(),
"select * from account where accountNum = ? ",
new BeanListHandler<Account>(Account.class),
accountNum);
} catch (SQLException e) {
throw new RuntimeException(e);
}
if (accounts == null || accounts.size() == 0) {
// 如果没有结果就返回null
return null;
} else if (accounts.size() > 1) {
// 如果结果集超过一个就抛异常
throw new RuntimeException("结果集不唯一,数据有问题");
} else {
// 如果有唯一的一个结果就返回
return accounts.get(0);
}
}
}
创建Account类
package entity;
public class Account {
private Integer id;
private String accountNum;
private Integer money;
// 省略getter&setter方法
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAccountNum() {
return accountNum;
}
public void setAccountNum(String accountNum) {
this.accountNum = accountNum;
}
public Integer getMoney() {
return money;
}
public void setMoney(Integer money) {
this.money = money;
}
}
创建AccountService接口类
package services;
public interface AccountService {
/**
* 转账
*
* @param sourceAccount 转出账户
* @param targetAccount 转入账户
* @param money 转账金额
*/
void transfer(String sourceAccount, String targetAccount, Integer money);
}
创建AccountServiceImpl类
package services.impl;
import dao.AccountDao;
import entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import services.AccountService;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
/**
* 转账
*
* @param sourceAccount 转出账户
* @param targetAccount 转入账户
* @param money 转账金额
*/
public void transfer(String sourceAccount, String targetAccount, Integer money) {
// 查询原始账户
Account source = accountDao.findAccountByNum(sourceAccount);
// 查询目标账户
Account target = accountDao.findAccountByNum(targetAccount);
// 原始账号减钱
source.setMoney(source.getMoney() - money);
// 目标账号加钱
target.setMoney(target.getMoney() + money);
// 更新原始账号
accountDao.updateAccount(source);
// 更新目标账号
accountDao.updateAccount(target);
System.out.println("转账完毕");
}
}
创建ConnecUtils类
package utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.SQLException;
@Component
public class ConnectionUtils {
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
@Autowired
private ComboPooledDataSource dataSource;
/**
* 获得当前线程绑定的连接
*
* @return
*/
public Connection getThreadConnection() {
try {
// 看线程是否绑了连接
Connection conn = tl.get();
if (conn == null) {
// 从数据源获取一个连接
conn = dataSource.getConnection();
// 和线程局部变量 绑定
tl.set(conn);
}
// 返回线程连接
return tl.get();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 把连接和当前线程进行解绑
*/
public void remove() {
tl.remove();
}
}
配置资源文件applicationContext.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:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
https://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
">
<!-- bean definitions here -->
<context:component-scan base-package="dao"/>
<context:component-scan base-package="services"/>
<context:component-scan base-package="utils"/>
<!--配置QueryRunner-->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--连接数据库的必备信息-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_aop"></property>
<property name="user" value="root"></property>
<property name="password" value="lfp123"></property>
</bean>
</beans>
创建AccounTest测试类
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 services.AccountService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class AccountTest {
@Autowired
private AccountService accountService;
@Test
public void testTransfer() {
accountService.transfer("622200001", "622200002", 100);
}
}
启动AccounTest测试类之前
启动AccounTest实现类之后