Caching InitialContext und DataSource in einer Java EE-Web-App
-
15-11-2019 - |
Frage
In der folgenden Anschluss- / J-Referenz für JDBC / MySQL vermuten es, dass wir die Instanzen von InitialContext und DataSource einspeichern.Würde es nur eine private statische Instanz machen, um das Caching zu lösen?Sollte man nicht mit Thread-Safety (falls überhaupt) besorgt sein müssen?Was ist der beste "Ort", um dies für eine Web-App (RESTLET + Glassfish / Java EE + MySQL) zu speichern?
Es gibt eine genericdao-Klasse, die das root der Datenzugriffsklassen sozusagen ist.Daher würden nur statische Instanzen tatsächlich das Problem lösen?Es würde einige der Methoden zwingen, statisch zu sein, die wir nicht wollen.Vorschläge ??
danke! generasacodicetagpre.
Lösung 2
Following up on BalusC's link, I can confirm that we could do the same thing when using Restlet. However, as per the code in the example to get the config instance you are passing in the ServletContext as an argument. Restlet is like 'another' framework that uses Servlets as an adapter to configure itself. So it'll be tricky to pass the ServletContext as an argument from somewhere else in the code (Restlet uses it's own Context object which is conceptually similar to ServletContext)
For my case a static method returning the cached datasource seems to be 'clean enough' but there could be other design/organization approaches.
Andere Tipps
If you're using JAX-RS, then you can use @Context
annotation.
E.g.
@Context
private ServletContext context;
@GET
@Path("whatevers")
public List<Whatever> getWhatevers() {
DataSource dataSource = Config.getInstance(context).getDataSource();
// ...
}
However, if the @Resource
annotation is also supported on your Restlet environment, you could make use of it as good.
@Resource(mappedName="jdbc/MySQLDB")
private DataSource dataSource
This is in turn technically better to be placed in an EJB which you in turn inject by @EJB
in your webservice.
@Stateless
public class WhateverDAO {
@Resource(mappedName="jdbc/MySQLDB")
private DataSource dataSource
public List<Whatever> list() {
// ...
}
}
with
@EJB
private WhateverDAO whateverDAO;
@GET
@Path("whatevers")
public List<Whatever> getWhatevers() {
return whateverDAO.list();
}