思路大概是这样子的,首先需要初始化Spring的容器,把所有注解类加入到容器中,Spring里的AnnotationConfigApplicationContext类完成了这一步,只需传入包路径就能完成我们需要的操作,
所以SpringPlugin的实现是这样的
package com.nmtx.plugins.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.jfinal.plugin.IPlugin;
/**
* spring
*
* @author lianghao
*
*/
public class SpringPlugin implements IPlugin {
private String[] packages;
public SpringPlugin(String... packages) {
this.packages = packages;
}
public boolean start() {
SpringInterceptor.setApplicationContext(new AnnotationConfigApplicationContext(packages));
return true;
}
public boolean stop() {
return true;
}
}
上面第一步就完成了,初始化完以后,需要拦截所有的Controller请求,注入所有的Controller属性,所以需要一个拦截器,具体实现如下
package com.nmtx.plugins.spring;
import java.lang.reflect.Field;
import javax.annotation.Resource;
import org.springframework.context.ApplicationContext;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
public class SpringInterceptor implements Interceptor {
private static ApplicationContext applicationContext;
public void intercept(Invocation ai) {
Controller controller = ai.getController();
Field[] fields = controller.getClass().getDeclaredFields();
for (Field field : fields) {
Object bean = null;
Resource resource = field.getAnnotation(Resource.class);
if (resource != null) {
String name = resource.name();
Class<?> classType = resource.type();
if (!classType.getName().equals("java.lang.Object")) {
bean = applicationContext.getBean(classType);
} else if (StrKit.notBlank(resource.name())) {
bean = applicationContext.getBean(name);
} else {
bean = applicationContext.getBean(field.getName() + "Impl");
}
try {
if (bean != null) {
field.setAccessible(true);
field.set(controller, bean);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
ai.invoke();
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static void setApplicationContext(ApplicationContext applicationContext) {
SpringInterceptor.applicationContext = applicationContext;
}
}
经过这两步,Spring集成就完成了,接下来就是怎么使用了,无需添加任何xml配置,只需添加如下配置即可
/**
* 定义插件,指定扫描路径
*/
@Override
public void configPlugin(Plugins me) {
me.add(new SpringPlugin("com.nmtx.manager"));
}
/**
* 添加全局拦截器
*/
@Override
public void configInterceptor(Interceptors me) {
me.add(new SpringInterceptor());
}
在Controller中和SpringMVC使用就没什么太大区别了具体使用如下
Controller层
package com.nmtx.manager.controller.permission;
import javax.annotation.Resource;
public class UserController extends Controller {
/** 只需一个注解**/
@Resource
private UserService userService;
}
Service层
/**也是一个注解**、
@Service
public class UserServiceImpl implements UserService {
@Resource
private User userDao;
}
Dao层
@Repository
public class User extends Model<User> {
}
Spring包依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.5.RELEASE</version>
<scope>provided</scope>
</dependency>