今回は実装編。
Serviceクラスはインタフェースを用意。
package examples.service; public interface LoginService { public boolean execute(String userId, String password); }
そして実装クラス。
ポイントは「@Service」をクラス名に付与すること。
package examples.service; import org.springframework.stereotype.Service; @Service("loginService") public class LoginServiceImpl implements LoginService{ public boolean execute(String userId, String password) { if("spring".equals(userId) && "spring".equals(password)) { return true; } return false; } }「@Service」は「@Component」と同じ機能を提供してますが、サービスクラスには明示的に
「@Service」を付与するのが良いでしょう。
ちなみにDaoクラスには「@Repository」、コントローラ(アクション)クラスには「@Controller」、
いずれにも当てはまらない場合に「@Component」を付与します。
そしてActionクラスです。
ここでのポイントは、DIしたいサービスクラスを宣言し、「@Autowired」を付与することです。
package examples.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.beans.factory.annotation.Autowired; import examples.form.LoginForm; import examples.service.LoginService; public class LoginAction extends Action { @Autowired private LoginService loginService = null; @Override public ActionForward execute(ActionMapping map, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // フォームからIDおよびパスワードを取得 LoginForm loginForm = (LoginForm)form; String userId = loginForm.getUserId(); String password = loginForm.getPassword(); // ログイン処理 boolean result = loginService.execute(userId, password); if(result){ // ログイン成功 return map.findForward("success"); } // ログイン失敗 return map.findForward("failure"); } }
ここまでのことを行えば、サービスクラスがDIされると思います。
0 件のコメント:
コメントを投稿