jfinal是国内的框架,是要支持一下,波哥强啊,一直维护做这个框架的迭代更新。框架是挺好用的,符合快速开发的需求,对一些小项目足够了,但一些大的项目,需要高灵活性,高扩展,就不那么适合了,这里参考波哥的文档,做了一下jfinal整合spring。
一、引入spring的jar包
二、jfinal配置中加入spring插件
JFinalConfig的配置:
@Override
public void configPlugin(Plugins me) {
......
//spring插件
me.add(new SpringPlugin("classpath*:spring/*.xml"));
}
@Override
public void configInterceptor(Interceptors me) {
......
//ioc拦截器
me.add(new IocInterceptor());
}
IocInterceptor拦截器:
import java.lang.reflect.Field;
import org.springframework.context.ApplicationContext;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
/**
* IocInterceptor.
*/
public class IocInterceptor implements Interceptor {
static ApplicationContext ctx;
public void intercept(Invocation ai) {
Controller controller = ai.getController();
Field[] fields = controller.getClass().getDeclaredFields();
for (Field field : fields) {
Object bean = null;
if (field.isAnnotationPresent(Inject.BY_NAME.class))
bean = ctx.getBean(field.getName());
else if (field.isAnnotationPresent(Inject.BY_TYPE.class))
bean = ctx.getBean(field.getType());
else
continue ;
try {
if (bean != null) {
field.setAccessible(true);
field.set(controller, bean);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
ai.invoke();
}
}
*/
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Inject.
*/
public class Inject {
private Inject() {}
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public static @interface BY_TYPE {}
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public static @interface BY_NAME {}
/*
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public static @interface IGNORE {}
*/
}
三、整合运用
在需要的地方加上@Before(IocInterceptor.class),jfinal切面是通过拦截器来完成的,在使用jfinal开发时,你会发现,会有很多的拦截器,功能上与spring aop差不多,对于事务管理和操作日记的通用功能可以通过jfinal拦截器增强处理。
@Before(IocInterceptor.class)
public class WebServiceController extends Controller {
private static final Logger logger = Logger.getLogger(WebServiceController.class);
@Inject.BY_NAME
private LogInfoService logInfoService;
}