@Stateless public class HelloService { }
public class UserMgr { @Inject private HelloService hello; public void doSomething() { hello.sayHello(); ... } }というように、スコープを付けた POJO を @Inject で Injection する。せいぜい @Named でインスタンスを使い分けるくらい
package com.mycompany.cdiexam;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.inject.Named;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Named
@Dependent
public class LoggerProducer {
@Produces
public Logger getLogger(InjectionPoint ip){
return LoggerFactory.getLogger(ip.getMember().getDeclaringClass().getName());
}
}
@Dependent は、Injection された側の Scope で管理されることを示すスコープpackage com.mycompany.cdiexam;
...
@WebServlet(name = "HelloServlet", urlPatterns = {"/HelloServlet"})
public class HelloServlet extends HttpServlet {
@Inject
private HelloCDI helloCdi;
@Inject
transient Logger logger;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
logger.info("Start Response");
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet HelloServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>" + helloCdi.hello("Az") + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
logger.info("End Response");
out.close();
}
}
....
<configuration>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<prudent>true</prudent>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>/Users/atsushi/GlassFish40/glassfish/domains/domain1/logs/app_%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%date %-5level %logger{35} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="FILE" />
</root>
</configuration>
[~/GlassFish40/glassfish/domains/domain1/logs]$ cat app_2015-01-10.log
2015-01-10 23:05:01,753 INFO com.mycompany.cdiexam.HelloServlet - Start Response
2015-01-10 23:05:01,756 INFO com.mycompany.cdiexam.HelloServlet - End Response
2015-01-10 23:05:48,909 INFO com.mycompany.cdiexam.HelloServlet - Start Response
2015-01-10 23:05:48,922 INFO com.mycompany.cdiexam.HelloServlet - End Response
@Produces public Logger getLogger(InjectionPoint ip){の ip から injection する側の Object が取得できている
きしだのはてな に曰く
@Named
@Dependent
public class EntityManagerProducer {
@PersistenceContext(unitName = "kis_PU")
@Produces
private EntityManager em;
}
@Named
@ApplicationScoped
public class BunruiDao {
@Inject
private EntityManager em;
@Transactional
public void persist(
@Valid TBunrui bunrui)
{
em.persist(bunrui);
}
}