異常拋出加強使用方法及案例

在說使用AOP面向切面編程的思想對代碼段進行加強處理以前,先說兩個理論知識點:html

—經常使用切入表達式模糊匹配解釋:

①public * addUser(com.pb.entity.User): 「*」表示匹配全部類型的返回值; 
②public void * (com.pb.eneity.User): 「*」表示匹配全部方法名;
③public void addUser(..): 「…」表示匹配全部參數個數和類型; 
④* com.pb.service.* . *(..):匹配com.pb.service包下全部類的全部方法; 
⑤* cpm.pb.service..*( ):匹配cpm.pb.service包及子包下全部類的全部方法。java

使用的時候能夠根據需求來設置切入點的匹配規則。spring

—加強處理類型:

①Before:前置加強處理,在目標方法前織入; 
②AfterReturning:後置加強處理,在目標方法正常執行後織入; 
③AfterThrowing:異常加強處理,在目標方法拋出異常後織入; 
④After:最終加強處理,不論方法是否拋出異常,都會在目標方法最後織入; 
⑤Around:環繞加強處理,在目標方法的先後均可以織入加強處理。數據庫

案例: express

1.首先有一個User的實體類,擁有如下幾個屬性:
編程

 private Integer id; // 用戶ID
private String username; // 用戶名
private String password; // 密碼
private String email; // 電子郵件  . //get和set方法省略   												



2.編寫bean四層代碼,除了daoImpl代碼與以前有所區別,其餘都同樣: 
dao:

	/** * 增長DAO接口,定義了所需的持久化方法 */
 public interface IDao {    public void save(User user);}											

daoImpl:

	/** * 用戶DAO類,實現IDao接口,負責User類的持久化操做 */
	public class UserDao implements IDao {   								public void save(User user) {        // 這裏並未實現完整的數據庫操做,僅爲說明問題
			System.out.println("保存用戶信息到數據庫");
 throw new RuntimeException("爲測試程序運行效果拋出的異常");
  //throw new SQLException("爲測試程序運行效果拋出的異常");    }}		       




biz:

	/** * 用戶業務接口,定義了所需的業務方法 */
	public interface IUserBiz {    public void addNewUser(User user);}

bizImpl:

	/** * 用戶業務類,實現對User功能的業務管理 */
	public class UserBiz implements IUserBiz {    // 聲明接口類型的引用,和具體實現類解耦合
	private IDao dao;    // dao 屬性的setter訪問器,會被Spring調用,實現設值注入
	public void setDao(IDao dao) {        this.dao = dao;    } 
	public void addNewUser(User user) {        // 調用用戶DAO的方法保存用戶信息
     dao.save(user);    }}	    	    	   	  	





在數據訪問層,我人爲的拋出了一個異常,用於測試異常的織入是否正常。那麼接下來,就來建立織入的程序類:

3.ErrorLogger 類:app

	/** * 經過ThrowsAdvice接口實現異常拋出加強 */
	public class ErrorLogger implements ThrowsAdvice {
	private static final Logger log = Logger.getLogger(ErrorLogger.class);
	public void afterThrowing(Method method, Object[] args, Object target,RuntimeException e) {
	log.error(method.getName() + " 方法發生異常:" + e);    }
	public void afterThrowing(Method method, Object[] args, Object target,SQLException ex) {
	log.error(method.getName() + " 方法發生異常:" + ex);    }}	    	    	       	    	        	






4.配置文件:

	<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	<!-- ↓↓引入aop相關命名空間↓↓ -->
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
	<!-- ↓↓引入aop相關命名空間↓↓ -->
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
	<bean id="dao" class="dao.impl.UserDao"></bean>
	<bean id="biz" class="biz.impl.UserBiz">
	<property name="dao" ref="dao"></property>
	</bean>
	<!-- ↓↓定義加強組件↓↓ -->
	<bean id="errorLogger" class="aop.ErrorLogger"></bean>
	<aop:config>
	<!-- ↓↓指定加強處理的範圍 ↓↓ -->
	<aop:pointcut id="pointcut" expression="execution(* biz.IUserBiz.*(..))" />
	<!-- ↓↓引用,裝配組件↓↓ -->
	<aop:advisor pointcut-ref="pointcut" advice-ref="errorLogger" />
	</aop:config>
	</beans>	 			






















5.最後,來編寫一個測試類Test,觸發異常加強,看看效果:

	public class Test {    
		/**     * @param args     */    
		public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		IUserBiz biz = (IUserBiz) ctx.getBean("biz");
		User user = new User();
		user.setId(1);
		user.setUsername("test");
		user.setPassword("123456");
		user.setEmail("test@pbdevj.com");
		biz.addNewUser(user);    }}		








6.執行後效果:





程序準確的捕捉到了異常並拋出。


測試

相關文章
相關標籤/搜索