基于注解的Spring的IOC,AOP,JDBC,事务的crud

为了综合的应用Spring,写一个crud案例,本次想法是能用注解就不用xml配置文件

配置Spring的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"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
     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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">


<!-- 基于注解的加载bean的扫描 -->
<context:component-scan base-package="/lhc"></context:component-scan>

<!-- 开启注解的aspectj的aop -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

<!-- 根据配置文件配置数据库 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring?allowMultiQueries=true
jdbc.username=root
jdbc.password=123
 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="jdbcUrl" value="${jdbc.url}"></property>
    <property name="driverClass" value="${jdbc.driver}"></property>
    <property name="user" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>
</bean>

<!-- 配置jdbcTemplate,依赖数据源 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"></property>
</bean>

<!-- 配置事务管理器,依赖数据源 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>

<!-- 开启基于注解的事务管理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>




</beans>

为上面的配置添加监听器,让服务器启动就加载Spring的bean对象

<?xml version="1.0" encoding="UTF-8"?>
<!-- needed for ContextLoaderListener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:bean.xml</param-value>
    </context-param>

    <!-- Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

接下来写一个domain对象

package lhc.domain;

import org.springframework.stereotype.Component;

@Component(value = "user")
public class User {
    private int id;
    private int balance;
    private String userName;
    private String password;


    public int getBalance() {
        return balance;
    }

    public void setBalance(int balance) {
        this.balance = balance;
    }

    public User(int id, String userName, String password, int balance) {
        super();
        this.id = id;
        this.userName = userName;
        this.password = password;
        this.balance = balance;
    }

    public User() {
        super();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", userName=" + userName + ", password="
                + password + ", balance=" + balance + "]";
    }



}

再写一个基于jdbcTemplate的DAO

package lhc.dao;

import java.util.List;

import javax.annotation.Resource;

import lhc.domain.User;

import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;


@Scope("singleton")
@Repository(value="dao" )
public class DAO {

    @Resource(name="jdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    //删除用户
    public void deleteById(int id){
        System.out.println("dao...delete..........");
        String sql ="delete from user where id =?";
        jdbcTemplate.update(sql,id);

    }
    //更新用户
    public void update (User user){
        System.out.println("更新用户");
        String sql="update user set user_name =?,password =?,balance=? where id=?";
        Object[] args =new Object[]{user.getUserName(),user.getPassword(),user.getBalance(),user.getId()};
        jdbcTemplate.update(sql, args);
    }
    //添加用户
    public void add(User user){
        System.out.println("dao增加用户");
        String sql ="insert into user (user_name ,password,balance) values(?,?,?)";
        Object[] args =new Object[]{
                user.getUserName(),user.getPassword(),user.getBalance()
        };
        jdbcTemplate.update(sql, args);
    }

    //查询单个用户
    public  User selectByName(String username){
        System.out.println("dao...select......");
        String sql= "SELECT * FROM USER WHERE user_name=?";
        RowMapper<User> userMapper =new BeanPropertyRowMapper<User>(User.class);
        //返回为list的集合
        //return jdbcTemplate.query(sql, userMapper, username);
        //返回单个对象
        return jdbcTemplate.queryForObject(sql, userMapper, username);
    }
    //查询所有用户
    public List<User> selectAll(){
        String sql ="select * from user ";
        //创建映射对象,多种方式
        //ParameterizedBeanPropertyRowMapper<User> userMapper2 = ParameterizedBeanPropertyRowMapper.newInstance(User.class);
        BeanPropertyRowMapper<User> userMapper = new BeanPropertyRowMapper<User>(User.class);
        //返回所有用户
        return jdbcTemplate.query(sql,userMapper);
    }
    //少钱
    public void lessMoney(String username,int num) {
        String sql ="update user set balance =balance-? where user_name=?";
        jdbcTemplate.update(sql, num,username);
    }
    //加钱
    public void addMoney(String username, int num){
        String sql ="update user set balance =balance +? where user_name=?";
        jdbcTemplate.update(sql, num,username);
    }

}

写一个Service,并为该Service开启事务

package lhc.service;

import java.util.List;

import javax.annotation.Resource;

import lhc.dao.DAO;
import lhc.domain.User;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
//事务只需要出现在service即可
@Transactional(isolation=Isolation.REPEATABLE_READ)
@Scope(value="singleton")
@Service(value="userService")
public class UserService {
    @Resource(name="dao")
    private DAO dao;

    public void add(User user){
        System.out.println("service...add...............");
        dao.add(user);
    }

    public void  update(User user) {
        System.out.println("service...update");
        dao.update(user);

    }
    public void deleteById (int id){
        dao.deleteById(id);
    }
    public User selectByName(String username){
        return dao.selectByName(username);
    }
    public List<User> selectAll() {
        return dao.selectAll();
    }

    public void  accountMoney (String lessname,String addname,int num) {
        dao.lessMoney(lessname, num);
        //模拟意外事故
        //int i=10/0;
        dao.addMoney(addname, num);
    }

}

写一个AOP增强Service

package lhc.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component(value="myAspect")
@Scope(value="singleton")
@Aspect
public class MyAspect {

    //切点
    @Pointcut(value="execution(* lhc.service.*.*(..))")
    private void myPointcut() {}

    //前置通知
    @Before(value="myPointcut()")//注意加()
    public void before() {
        System.out.println("before....");
    }

    //后置通知
    @AfterReturning(value="myPointcut()")
    public void afterReturning(){

        System.out.println("afterReturn.........");
    }


    //环绕通知,方法执行前后的通知
    @Around(value="myPointcut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{

        System.out.println("before...around");

        Object proceed = proceedingJoinPoint.proceed();

        System.out.println("after...around");
        return proceed;
    }

    //出异常后的通知
    @AfterThrowing(value="myPointcut()",throwing="e")
    public void afterThrowing(Throwable e){

        System.out.println("出现异常,哎哟,异常为"+e.getMessage());
    }


    //最后通知
    @After(value="myPointcut()")
    public void after() {
        System.out.println("after...");
    }
}

最后写一个测试类

package spring.test;

import javax.annotation.Resource;

import lhc.service.UserService;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


//spring对junit的支持,使用junit4的最佳方式
@RunWith(SpringJUnit4ClassRunner.class)
//加载配置文件的最佳方式
@ContextConfiguration("classpath:bean.xml")
public class SpringTest {

    //使用前要注入该属性
    @Resource(name="userService")
    private UserService userService;

    @Test
    public void test1(){

        //用注解代替得到bean对象
        //ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        //UserService userService = (UserService)context.getBean("userService");

        //更新用户
//      User user = new User("张三","abcd",5555);
//      userService.update(user);
        //删除用户
        //userService.deleteById(8);

        //添加用户
//      User user = new User(0,"李四","abcd",5555);
//      userService.add(user);

        //查询单个用户
//      User user = userService.selectByName("李四");
//      System.out.println(user);

//      //查询所有用户
//      List<User> selectAll = userService.selectAll();
//      System.out.println(selectAll);
//      
        //模拟转账事务
        userService.accountMoney("jerry", "jack", 1000);
    }
}

猜你喜欢

转载自blog.csdn.net/lhc0512/article/details/79168451
今日推荐