spring-mybatis整合基于注解

1. 注解使用

@Service 业务类专用
@Repository DAO实现类专用
@Controller web层专用
@Component 通用,一般用于自己写的类
@Scope 用户控制bean的创建模式
部分可以省略

package com.qianfeng.service;

import com.qianfeng.dao.UserDAO;
import com.qianfeng.pojo.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

@Service  // 
//@Scope("prototype")  原型模式
//@Service("us") //自定义beanId
@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false,rollbackFor = Exception.class) //当前类中的所有方法,都切入事务
public class UserServiceImpl implements UserService{

//    @Autowired
    @Resource
    private UserDAO userDAO;

    /*@Autowired //基于类型为当前属性,自动注入
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }*/

    //则类上的事务属性,对此方法无效
    @Transactional(propagation = Propagation.SUPPORTS)
    public User queryUserById(Integer id) {
        return userDAO.queryUserById(id);
    }

    @Override
    public List<User> queryUsers() {

        return userDAO.queryUsers();
    }

    @Override
    public Integer insertUser(User user) {
        Integer integer = userDAO.insertUser(user);
        return integer;
    }
}

要将service层出现的所有异常都转为RuntimeException,这样在出现异常的时候能够回滚

@Autowired基于类型自动注入** **@Resource` 基于名称自动注入**

更便捷的注入方式 !!

public class UserServiceImpl implements UserService {
	...
	//@Resource(name="userService")//将id=userService的bean注入给此属性
	//此属性要求工厂,基于名称自动注入
	//@Resource //set/get可省略
	//此属性要求工厂,基于类型自动注入
	@Autowired //set/get可省略
	private UserDao userDao;
	...
}

@Transactional` 用于为业务中切入事务**

工厂配置中的

/类中的每个方法都切入事务(有自己的事务控制的方法除外)
@Transactional(isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED,readOnly=false,rollbackFor=Exception.class)
public class UserServiceImpl implements UserService {
	...
    //该方法自己的事务控制,仅对此方法有效
	@Transactional(propagation=Propagation.SUPPORTS)
	public List<User> queryAll() {
		return userDao.queryAll();
	}
	public void save(User user){
		userDao.save(user);
	}
}

2. 注解需要的配置



<context:component-scan base-package="com.zhj">context:component-scan>


<tx:annotation-driven transaction-manager="txManager"/>

3. @AspectJ

/**
 * 日志切面类
 */
@Aspect //声明当前组件为一个切面组件
@Component //声明当前组件
@Order(2)
public class MyLogAspect {

    //定义切入点
    @Pointcut("execution(* com.qianfeng..UserServiceImpl.*(..))")
    public void log04(){}

    //定义前置额外功能
    @Before("log04()")
    public void mylog(JoinPoint jp){
        String methodName = jp.getSignature().getName();
        System.out.println(methodName+" 于 "+new Date()+" 被访问啦");
    }
}

@Aspect //声明当前组件为一个切面组件
@Component //声明当前组件
@Order(1)
public class MyTestAspect {

    //定义切入点
    @Pointcut("execution(* com.qianfeng..UserServiceImpl.*(..))")
    public void pc04(){}

    //定义前置额外功能
    @Before("pc04()")
    public void mylog(JoinPoint jp){
        String methodName = jp.getSignature().getName();
        System.out.println("before~~~~");
    }

    // return ="ret" 将目标的返回值赋值给 ret形参,定义后置额外功能
    @AfterReturning(value = "pc04()",returning = "ret")
    public void myAfter(Object ret){
        System.out.println("myAfter~~~~, ret:"+ret);
    }

    @Around("pc04()") // 定制环绕额外功能
    public Object myInterceptor(ProceedingJoinPoint p) throws Throwable {
        System.out.println("interceptor1~~~~");
        Object ret = p.proceed();//调用核心逻辑
        System.out.println("interceptor2~~~~");
        return ret;
    }

    //定义异常额外功能
    @AfterThrowing(value="pc04()",throwing = "ex")
    public void myThrows(Exception ex){
        System.out.println("出错啦,"+ex.getMessage());
    }
}

添加如下配置:


    <context:component-scan base-package="com.qianfeng"/>
    
    <tx:annotation-driven transaction-manager="tx"/>

    
    <aop:aspectj-autoproxy/>

4. 与web集成

4.1 ContextLoaderListener

核心,注册ContextLoaderListener

准备工作:


<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-webartifactId>
    <version>4.3.6.RELEASEversion>
dependency>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>

<context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
context-param>

4.2 Servlet集成工厂

public class UserServlet extends HttpServlet {
    // 获取项目启动时随之启动的,存储于ServletContext中的工厂对象,
    private ApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
    // 从工厂中获取Service组件
    private UserService userService = context.getBean("userService",UserService.class);
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws 
        ServletException, IOException {
        List<User> users = userService.queryUsers();
        req.setAttribute("users",users);
        req.getRequestDispatcher("/users.jsp").forward(req,resp);
    }
}

你可能感兴趣的:(第三阶段)