当我想用@PostConstruct调用方法时,不会调用该方法。我没有从服务器收到任何错误或日志。我是否必须添加一些配置xml文件或添加其他注释才能调用该方法?
的Serlvet:
public class PersonServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(PersonServlet.class);
@EJB
Storage storage;
protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
try {
HttpSession session = req.getSession(true);
storage = (Storage) session.getAttribute(Storage.class.getName());
if (storage == null) {
storage = new Storage();
session.setAttribute(Storage.class.getName(), storage);
}
// create odata handler and configure it with CsdlEdmProvider and Processor
OData odata = OData.newInstance();
ServiceMetadata edm = odata.createServiceMetadata(new PersonEdmProvider(), new ArrayList<EdmxReference>());
ODataHttpHandler handler = odata.createHandler(edm);
handler.register(new PersonEntityCollectionProcessor(storage));
handler.register(new PersonEntityProcessor(storage));
handler.register(new PersonPrimitiveProcessor(storage));
// let the handler do the work
handler.process(req, resp);
} catch (RuntimeException e) {
LOG.error("Server Error occurred in ExampleServlet", e);
throw new ServletException(e);
}
}
}
的PersonDAO
@Stateless
public class PersonDAO {
@PersistenceContext
private EntityManager em;
public List<Person> getAllPersons() {
return
em.createQuery("SELECT p FROM T_Person p", Person.class).getResultList();
}
}
存储
@Stateless
public class Storage {
@EJB
PersonDAO psDAO;
private List<Entity> personList;
public Storage() {
personList = new ArrayList<Entity>();
}
@PostConstruct
private void initSampleData(){
psDAO.getAllPersons();
}
}
PersonEntityCollectionProcessor:
public class PersonEntityCollectionProcessor implements EntityCollectionProcessor {
private OData odata;
private ServiceMetadata serviceMetadata;
private Storage storage;
public PersonEntityCollectionProcessor(Storage storage) {
this.storage = storage;
}
public void init(OData odata, ServiceMetadata serviceMetadata) {
this.odata = odata;
this.serviceMetadata = serviceMetadata;
}
}
答案 0 :(得分:4)
我认为问题出在你的代码的这一部分:
storage = (Storage) session.getAttribute(Storage.class.getName());
if (storage == null) {
storage = new Storage();
session.setAttribute(Storage.class.getName(), storage);
}
使用此方法,您可以创建Storage
的非托管实例,而不是使用注入的实例,因此不会调用@PostConstruct
。
如果执行此代码时Storage
通过@EJB
注入的实例为null
,则您可能会遇到注入问题。
你可以删除这5行,它应该工作。您不需要在会话中手动保存实例。
答案 1 :(得分:3)
大多数EJB都是懒惰地初始化的,因此只有在实际使用该bean的实例时才会首先调用@PostConstruct。
那说;你永远不会在servlet的存储中使用实际的sessionbean,所以不需要调用@PostConstruct
您从会话中覆盖它,或重新创建它
(function($) {
$(function() {
$(".container").each(function() {
var container = $(this);
var gallery = container.children(".gallery");
container.children(".info").appendTo(gallery);
gallery.children(".thumbnails").appendTo(container);
});
});
})(jQuery);