CDI技术第七步 生命周期管理
其实生命周期的管理相当简单啊
就是两个注解
@PostConstruct与@PreDestroy
那么我们来试一试喽
package com.rschy.cdilifecycle.web;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.RequestScoped;
@RequestScoped
public class HelloService {
@PostConstruct
public void init() {
System.out.println("Creating...");
}
@PreDestroy
public void destroy() {
System.out.println("Destroying...");
}
public String greeting() {
return "Hello, world!";
}
}
这里我使用的是无接口的bean,其实CDI的bean是不需要接口的。
再写个servlet试一试。
package com.rschy.cdilifecycle.web;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/hello.html")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private @Inject HelloService service;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().append(service.greeting());
}
}
好运行一下
在glassfish的控制台果断打印了下面的东西