为什么PostConstruct在Spring中执行了两次

sr4lhrrt  于 2022-10-30  发布在  Spring
关注(0)|答案(1)|浏览(292)

我正在使用Spring开发一个Web应用程序,我只是在启动时使用了@PostConstruct@Bean机制来调用一个函数。

public class MyCache<T> {
    @PostConstruct
    public void init() {
        System.out.println("inittttttttttt");
        // something
    }
}

@Configuration
@EnableScheduling
public class AppConfig {
    @Bean
    public MyCache<MyData> myCache() {
        return new MyCache<MyData>();
    }
}

public class TextFilter {
    private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    private MyCache<MyData> cache;

    public TextFilter() {
        this.context.scan("com.sensitive_words.utils");
        this.context.refresh();
        this.cache = this.context.getBean(MyCache.class);
    }

    public String filter(String originalText) {
        return this.cache.get().filter(originalText);
    }
}

如您所见,我创建了一个Bean并在类TextFilter中使用了该Bean。
但是,我发现函数init()执行了两次。

2022-10-30 13:53:38.837  INFO 106994 --- [           main] y.c.s.SensitiveWordsApplication          : Starting SensitiveWordsApplication using Java 11.0.16 on yves-Inspiron-5488 with PID 106994 (/home/yves/java_ws/sensitive_words/target/classes started by yves in /home/yves/java_ws/sensitive_words)
2022-10-30 13:53:38.839  INFO 106994 --- [           main] y.c.s.SensitiveWordsApplication          : No active profile set, falling back to 1 default profile: "default"
2022-10-30 13:53:39.545  INFO 106994 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8090 (http)
2022-10-30 13:53:39.559  INFO 106994 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-10-30 13:53:39.560  INFO 106994 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.68]
2022-10-30 13:53:39.654  INFO 106994 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-10-30 13:53:39.654  INFO 106994 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 763 ms
inittttttttttt
2022-10-30 13:53:39.769  INFO 106994 --- [           main] s.a.ScheduledAnnotationBeanPostProcessor : No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
inittttttttttt
2022-10-30 13:53:40.080  INFO 106994 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8090 (http) with context path ''
2022-10-30 13:53:40.096  INFO 106994 --- [           main] y.c.s.SensitiveWordsApplication          : Started SensitiveWordsApplication in 1.64 seconds (JVM running for 2.341)

你能帮我吗?

bnl4lu3b

bnl4lu3b1#

我看到您正在设置两个不同的Spring应用程序上下文

  1. SensitiveWordsApplication为您完成
    1.在代码中手动创建的AnnotationConfigApplicationContext context
    这似乎就是原因,默认情况下,每个容器创建一个单例Bean。

相关问题