JFinal框架也整合了Spring框架,下面实现JFinal怎么去配置Spring框架。在JFinal中整合Spring使用到的类是SpringPlugin和IocInterceptor类
SpringIplugin类:
SpringPlugin 是作为 JFinal 的 Plugin 而存在的,所以使用时需要在 JFinalConfig 中配置SpringPlugin,以下是 Plugin 配置示例代码:
@Override public void configPlugin(Plugins me) {
<span style="white-space:pre"> </span>//配置Spring挂件 me.add(new SpringPlugin()); }
以前学习Spring养成了习惯将Spring的配置放在src下,这里我还是放在src的spring包中,如下:
@Override public void configPlugin(Plugins me) { //配置Spring挂件, 自动找spring包中所有的xml配置文件 me.add(new SpringPlugin("classpath*:spring/*.xml")); }IocInterceptor类:
package com.tenghu.core.controller; import java.util.List; import com.jfinal.aop.Before; import com.jfinal.core.Controller; import com.jfinal.plugin.spring.Inject; import com.jfinal.plugin.spring.IocInterceptor; import com.tenghu.core.model.Users; import com.tenghu.core.service.LoginService; import com.tenghu.core.validator.LoginValidator;
@Before(IocInterceptor.class) public class IndexController extends Controller{ @Inject.BY_NAME private LoginService loginService; public void index(){ List<Users> testList=Users.dao.find("select * from users"); setAttr("testList", testList); render("login.html"); } public void login(){ String username=getPara("name"); String password=getPara("password"); if(loginService.login(username, password)){ renderText("登录成功"); }else{ renderText("登录失败"); } } }上例将对 loginService 按属性名称进行注入。注解@Inject.BY_NAME 按属性名进行注入,@Inject.BY_TYPE 按类型进行注入。不指定注入类型时将不会进行注入。
登录服务接口与实现类:
package com.tenghu.core.service; public interface LoginService { /** * 登录处理 */ public boolean login(String username,String password); }
package com.tenghu.core.service.impl; import com.tenghu.core.service.LoginService; public class LoginServiceImpl implements LoginService{ /** * 登录处理 */ public boolean login(String username, String password) { if("admin".equals(username)&&"admin".equals(password)){ return true; } return false; } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
<span style="white-space:pre"> default-autowire="byName"</span>> <bean id="loginService" class="com.tenghu.core.service.impl.LoginServiceImpl"/> </beans>配置完成