injectinterceptor.java

来自「精通EJB3源码」· Java 代码 · 共 41 行

JAVA
41
字号
package com.foshanshop.ejb3.impl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import javax.annotation.PostConstruct;
import javax.ejb.EJBException;
import javax.interceptor.InvocationContext;

import com.foshanshop.ejb3.Person;
import com.foshanshop.ejb3.PersonInject;

public class InjectInterceptor {
	   @PostConstruct
	   public void jndiInject(InvocationContext invocation) {
	      Object target = invocation.getTarget( );
	      Field[] fields = target.getClass().getDeclaredFields( );
	      Method[] methods = target.getClass().getDeclaredMethods( );

	      try {
	         for (Method method : methods) {
	        	PersonInject inject = method.getAnnotation(PersonInject.class);
	            if (inject != null) {
	               method.setAccessible(true);
	               method.invoke(target, new Person(inject.name(), inject.age()));
	            }
	         }
	         for (Field field : fields) {
	        	PersonInject inject = field.getAnnotation(PersonInject.class);
	            if (inject != null) {
	               field.setAccessible(true);
	               field.set(target, new Person(inject.name(), inject.age()));
	            }
	         }
	         invocation.proceed( );
	      } catch (Exception ex) {
	         throw new EJBException("执行@PersonInject失败", ex);
	      }
	   }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?