1. 程式人生 > >6.IoC和AOP使用拓展:使用註解實現IoC的配置

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註解定義環繞增強