import javax.enterprise.inject.Produces; class FacesContextProducer { @Produces @RequestScoped FacesContext getFacesContext() { return FacesContext.getCurrentInstance(); } }
@Transactional @Interceptor public class TransactionInterceptor { @Resource UserTransaction transaction; @AroundInvoke public Object manageTransaction(InvocationContext ctx) throws Exception { ... } }
@SessionScoped public class Login implements Serializable { @Inject Credentials credentials; @PersistenceContext EntityManager userDatabase; ... }
在Java EE @PostConstruct和@PreDestroy的生命周期回调也支持所有ManagedBean。所有资源注入完成后@PostConstruct方法会被调用。
当然,我们建议组件环境注入是被用来定义CDI资源,并且在应用程序代码中以类型安全的注入。public class LoginServlet extends HttpServlet { @Inject Credentials credentials; @Inject Login login; //只是示例,实际开发要避免重写Service方法, //一为了保留HttpServlet默认实现的缓存协商的机制(HTTP 304); //二就是禁用你没有在servlet中重写的方法,例如post、head等,这样就从一定程度上提高了安全性 @Override public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { credentials.setUsername(request.getParameter("username")): credentials.setPassword(request.getParameter("password")): login.login(); if ( login.isLoggedIn() ) { response.sendRedirect("/home.jsp"); } else { response.sendRedirect("/loginError.jsp"); } } }
servlet的实例共享所有传入的线程.
@Transactional @MessageDriven public class ProcessOrder implements MessageListener { @Inject Inventory inventory; @PersistenceContext EntityManager em; public void onMessage(Message message) { ... } }
请注意,消息驱动bean不能注入@SessionScoped或@ConversationScoped的Bean。只有@RequestScoped和@ApplicationScopedBean可用。
import javax.jms.ConnectionFactory; import javax.jms.Queue; public class OrderResources { @Resource(name="jms/ConnectionFactory") private ConnectionFactory connectionFactory; @Resource(name="jms/OrderQueue") private Queue orderQueue; @Produces @Order public Connection createOrderConnection() throws JMSException { return connectionFactory.createConnection(); } public void closeOrderConnection(@Disposes @Order Connection connection)throws JMSException { connection.close(); } @Produces @Order public Session createOrderSession(@Order Connection connection)throws JMSException { return connection.createSession(true, Session.AUTO_ACKNOWLEDGE); } public void closeOrderSession(@Disposes @Order Session session)throws JMSException { session.close(); } @Produces @Order public MessageProducer createOrderMessageProducer(@Order Session session)throws JMSException { return session.createProducer(orderQueue); } public void closeOrderMessageProducer(@Disposes @Order MessageProducer producer)throws JMSException { producer.close(); } }
使用示例:
@Inject Order order; @Inject @Order MessageProducer producer; @Inject @Order Session orderSession; public void sendMessage() { MapMessage msg = orderSession.createMapMessage(); msg.setLong("orderId", order.getId()); ... producer.send(msg); }
注入的JMS对象的生命周期完全由容器控制。
beans.xml文件必须位于:META-INF/beans.xml(jar包),或者,WEB-INF/beans.xml或WEB-INF/classes/META-INF/beans.xml(war包)。
Over.