简体   繁体   English

Spring在Main中使用任何bean之前从Configuration类加载/运行每个bean?

[英]Spring load/runs every beans from Configuration class before any bean is used in main?

It's true that Spring load/runs every beans from Configuration class before any bean is used in main? 确实,在main中使用任何bean之前,Spring会从Configuration类加载/运行每个bean。 We got something abstract like: 我们得到了一些抽象的东西:

  @Configuration
  public class Config {
     @Bean
     public String aha() {
     System.out.println("ss1s");
     return "sss";
    }
}

And in main i got only this: 总的来说,我只有这个:

public static void main(String[] args) {
        // TODO Auto-generated method stub
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
    }

I didnt use any beans in main but after run, in console i have "ss1s". 我没有在main中使用任何bean,但是在运行后,在控制台中我有“ ss1s”。 That behaviour are correct? 那是正确的行为吗?

It is true. 是真的。 By default Spring eagerly initialize all beans. 默认情况下,Spring急切地初始化所有bean。

To initialize beans lazily you can use the @Lazy annotation, like follows 要延迟初始化bean,可以使用@Lazy批注,如下所示

    @Bean
    @Lazy
    public String aha() {
       ...
    }

Beans are not lazy by default. Bean在默认情况下不是惰性的。 However, as far as annotations are concerned it seems like currently, annotations do not support it. 但是,就注释而言,当前似乎不支持注释。 http://forum.springsource.org/showthread.php?t=62931 http://forum.springsource.org/showthread.php?t=62931

Spring's next version though seems to have something in store http://jira.springframework.org/browse/SJC-263 虽然Spring的下一版本似乎已经在商店中提供了一些东西http://jira.springframework.org/browse/SJC-263

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在任何其他Bean之前先弹簧加载一个Bean - Spring Load A Bean Before Any Other Bean Spring JavaConfig:通过“直接”调用Configuration类/ bean来检索bean - Spring JavaConfig: Retrieving beans by calling Configuration class/bean “directly” 如何在配置类中的bean之前在继承的XML配置中加载bean(Spring中的集成测试) - How to load beans in inherited XML config, before beans in Configuration classes (integration tests in Spring) Spring Boot从另一个模块加载bean之前 - Spring Boot load beans from a different module before 如何从主类访问Spring Bean - How to access Spring beans away from main class 配置问题:Bean名称“ dataSource”已在此使用 <beans> 元件 - Configuration issue : Bean name “dataSource” is already used in this <beans> element Spring Boot应用程序需要在@Configuration类中为使用@Value定义默认bean? - Spring Boot application requires defining default beans in a @Configuration class for @Value to be used? 如何在无web.xml配置的情况下通过@Configuration使Jersey 2 / Spring 4加载bean - How to make Jersey 2 / Spring 4 load beans from @Configuration on a no web.xml configuration Spring Bean配置:如何将Bean标记为必需/可选? - Spring Bean Configuration: How to mark beans as mandatory/optional? Spring配置:2个具有相同类引用的bean - Spring Configuration: 2 beans with same class reference
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM