You can use CDI (Injection Dependency Injection) - for example, Weld or run the program on some JEE server (TomEE, JBoss, etc.). The following is an example of working with databases.
Use the appropriate @ ... Scoped annotation (ApplicationScoped, SessionScoped, etc.) in your class, as you prefer, for example:
@ApplicationScoped public class MyDatabaseFactory implements Serializable {}
Do what you would like to do in the constructor in some method annotated with @PostConstruct :
@PostConstruct private void initializeObjectsOrConnections() {
Add your object using the @Inject annotation to other places (if you want):
public class MyApplication { @Inject MyDatabaseFactory databaseFactory;
Clearing, destroying objects, and disconnecting from the database — what you wanted to do in the destructor from C ++ in the method annotated with the @PreDestroy class of the MyDatabaseFactory class, for example:
@PreDestroy private void destroyObjectsOrCloseConnections() {
It is very simple to use, and in Java we have the equivalent of a destructor from C ++.
Floatoverflow
source share