Spring Advent Calendar 5日目の記事です。
昨日も僕でしたね。
今日は誰得ネタです。
EJBでつくった業務ロジックをSpring MVCのControllerにインジェクションしたいときにどうするか。
EJB
超適当。Local Stateless Session Beanです。
package hoge.domain.service.hello;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
@Stateful
public class HelloService {
public String hello(String message) {
return "Hello " + message + "(" + count + ")!";
}
}
Bean定義
Java EE6からEJBは「java:global/war名/EJB名」でJNDIアクセスできます。
<jee:jndi-lookup id="helloService" jndi-name="java:global/spring-ejb/HelloService" />
を定義しておけばSpringでEJBを管理できます。
Controller
@Inject
でEJBをインジェクションできます。
package hoge.app.welcome;
import hoge.domain.service.hello.HelloService;
import java.util.Locale;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory
.getLogger(HomeController.class);
@Inject
HelloService helloService;
@RequestMapping(value = "/", method = {RequestMethod.GET, RequestMethod.POST})
public String home(Locale locale, Model model, @RequestParam(value = "m", required = false, defaultValue = "you") String m) {
String message = helloService.hello(m);
model.addAttribute("message", message);
return "welcome/home";
}
}
SpringでもEJBつかえますね!(Statefull Session Beanもいけるのかな・・・?)
明日も・・・おれか?