Enterprise Intermédiaire

Remplace les Singleton EJB par des beans CDI @ApplicationScoped pour une gestion d'état partagé plus simple.

✕ Java EE
@Singleton
@Startup
@ConcurrencyManagement(
    ConcurrencyManagementType.CONTAINER)
public class ConfigCache {
    private Map<String, String> cache;

    @PostConstruct
    public void load() {
        cache = loadFromDatabase();
    }

    @Lock(LockType.READ)
    public String get(String key) {
        return cache.get(key);
    }

    @Lock(LockType.WRITE)
    public void refresh() {
        cache = loadFromDatabase();
    }
}
✓ Jakarta EE 8+
@ApplicationScoped
public class ConfigCache {
    private volatile Map<String, String> cache;

    @PostConstruct
    public void load() {
        cache = loadFromDatabase();
    }

    public String get(String key) {
        return cache.get(key);
    }

    public void refresh() {
        cache = loadFromDatabase();
    }
}
Un problème avec ce code ? Dites-le nous.
🪶

Moins de bruit d'annotations

Sans @ConcurrencyManagement, @Lock ni @Startup — juste une seule annotation @ApplicationScoped.

🔧

Concurrence flexible

Utilisez les verrous de java.util.concurrent ou volatile pour exactement la sécurité thread dont vous avez besoin.

🧪

Tests simples

Les beans CDI simples peuvent être instanciés directement dans les tests sans conteneur EJB.

Ancienne Approche
@Singleton EJB
Approche Moderne
@ApplicationScoped CDI
Depuis JDK
11
Difficulté
Intermédiaire
Singleton EJB vs CDI @ApplicationScoped
Disponible

Disponible depuis Jakarta EE 8 / Java 11

Les Singleton EJB regroupent la gestion de la concurrence (@Lock, @ConcurrencyManagement) et l'initialisation précoce (@Startup) dans le conteneur EJB. Un bean CDI @ApplicationScoped atteint le même cycle de vie d'instance unique avec beaucoup moins de cérémonie. Quand le contrôle de la concurrence est nécessaire, les utilitaires standard de java.util.concurrent offrent un contrôle plus granulaire que les annotations de verrouillage EJB.

Partager 𝕏 🦋 in