Guide rapide sur l’annotation Spring @Lazy

Guide rapide sur l'annotation Spring @Lazy

1. Vue d'ensemble

By default, Spring creates all singleton beans eagerly at the startup/bootstrapping of the application context. La raison en est simple: éviter et détecter toutes les erreurs possibles immédiatement plutôt qu'au moment de l'exécution.

Cependant, il y a des cas où nous devons créer un bean, non pas au démarrage du contexte de l'application, mais lorsque nous le demandons.

Dans ce rapide tutoriel, nous allons discuter de l'annotation@Lazy de Spring.

2. Initialisation paresseuse

L'annotation@Lazy est présente depuis la version Spring 3.0. Il existe plusieurs façons de demander au conteneur IoC d'initialiser un bean paresseux.

2.1. Classe@Configuration

When we put @Lazy annotation over the @Configuration class, it indicates that all the methods with @Bean annotation should be loaded lazily.

C'est l'équivalent de l'attributdefault-lazy-init= "true _" _ de la configuration XML.

Jetons un œil ici:

@Lazy
@Configuration
@ComponentScan(basePackages = "com.example.lazy")
public class AppConfig {

    @Bean
    public Region getRegion(){
        return new Region();
    }

    @Bean
    public Country getCountry(){
        return new Country();
    }
}

Voyons maintenant la fonctionnalité:

@Test
public void givenLazyAnnotation_whenConfigClass_thenLazyAll() {

    AnnotationConfigApplicationContext ctx
     = new AnnotationConfigApplicationContext();
    ctx.register(AppConfig.class);
    ctx.refresh();
    ctx.getBean(Region.class);
    ctx.getBean(Country.class);
}

Comme nous le voyons, tous les haricots sont créés uniquement lorsque nous les demandons pour la première fois:

Bean factory for ...AnnotationConfigApplicationContext:
...DefaultListableBeanFactory: [...];
// application context started
Region bean initialized
Country bean initialized

Pour ne l'appliquer qu'à un bean spécifique, supprimons les@Lazy d'une classe.

Ensuite, nous l’ajoutons à la configuration du haricot désiré:

@Bean
@Lazy(true)
public Region getRegion(){
    return new Region();
}

2.2 With @Autowired

Avant de continuer, consultez ces guides pour les annotations@Autowired et@Component.

Ici,in order to initialize a lazy bean, we reference it from another one.

Le haricot que nous voulons charger paresseusement:

@Lazy
@Component
public class City {
    public City() {
        System.out.println("City bean initialized");
    }
}

Et c'est la référence:

public class Region {

    @Lazy
    @Autowired
    private City city;

    public Region() {
        System.out.println("Region bean initialized");
    }

    public City getCityInstance() {
        return city;
    }
}

Notez que le@Lazy est obligatoire aux deux endroits.

Avec l'annotation@Component sur la classeCity et en la référençant avec@Autowired:

@Test
public void givenLazyAnnotation_whenAutowire_thenLazyBean() {
    // load up ctx appication context
    Region region = ctx.getBean(Region.class);
    region.getCityInstance();
}

Ici,the City bean is initialized only when we call the getCityInstance() method.

3. Conclusion

Dans ce rapide didacticiel, nous avons appris les bases de l'annotation@Lazyde Spring. Nous avons examiné plusieurs façons de le configurer et de l’utiliser.

Comme d'habitude, le code complet de ce guide est disponibleover on GitHub.