6.IoC和AOP使用拓展:使用注解实现IoC的配置

使用注解配置信息需先启动Spring容器:

先添加context命名空间的声明:在添加以下的话
<context:component-scan base-package="service,dao"/>

1.使用注解定义Bean

@Component(“userDao”)的作用于在XML配置文件中编写《bean id=“userDao” class=“dao.impl.UserDaoImpl”/》等效
@Repository:用于标注Dao类
@Service:用户标注业务类
@Controller:用于标注控制器类

2.实现注解实现Bean组件装配

public class UserServiceImpl implements UserService {
@Autowired
@Qualifier("userDao")
	private UserDao dao;
}

@Autowired:为dao属性注入所以来的对象,spring将直接对到属性进行赋值
@Qualifier(“userDao”):指定Bean主键所指定bean

java标准注解完成装配

@Resource:跟Qualifier用法作用一样

注解定义切面

使用注解完成装配首先导入aop命名空间,在配置文件中添加<aop:aspectj-autoproxy/》元素,就可以启动对于@AspectJ注解的支持

AspectJ简介:
AspectJ是一个面向切面的框架,他拓展了java语言,定义了AOP语法,能够在编译器提供代码的织入,所以他有一个专门的编译器用来生成遵守字节编码规范的Class文件

import java.util.Arrays;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class UserServiceLogger {
	private static final Logger log = Logger.getLogger(UserServiceLogger.class);

	@Before("execution(* service.userSerivce.*(..))")
	public void before(JoinPoint jp) {
		log.info("调用 " + jp.getTarget() + "的" + jp.getSignature().getName()
				+ "方法。方法入参 " + Arrays.toString(jp.getArgs()));
	}

	@AfterReturning(pointcut = "execution(* service.userSerivce.*(..))", returning = "result")
	public void afterReturning(JoinPoint jp, Object result) {
		log.info("调用" + jp.getTarget() + "的 " + jp.getSignature().getName()
				+ "方法。方法返回t值" + result);
	}

}

@Aspect注解将UserServiceLogger定义切面
@Before注解将before()方法定义为前置增强
@AfterReturnig注解将afterReturning()方法定义为后置增强
@AfterThrowing注解可以定义异常抛出增强

@AfterThrowing(pointcut = "execution(* service.userSerivce.*(..))", throwing="e")
	public void afterReturning(JoinPoint jp, RuntimeException e) {
		log.info("调用" + jp.getTarget() + "的 " + jp.getSignature().getName()
				+ "方法。方法返回t值" + e);
	}

@After注解定义最终增强

@After(pointcut = "execution(* service.userSerivce.*(..))", returning = "result")
	public void afterReturning(JoinPoint jp) {
		log.info(jp.getSignature().getName()
				+ "方法结束执行" + result);
	}

@Around注解定义环绕增强

猜你喜欢

转载自blog.csdn.net/qq_43051879/article/details/84863853