有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring是否触发静态初始化块?

我有一个类,它使用一个静态初始化块来做一些事情。我的理解是,这个块是在类被加载时执行的,这个类是通过从类中调用一些方法触发的

我的问题是,这种静态初始化是否可以从spring之类的框架触发,这些框架查看类以检查它们的注释等等


共 (1) 个答案

  1. # 1 楼答案

    类路径扫描不会触发静态初始化块,但创建组件会:

    @Component
    public class ComponentClass{
        static{
            System.out.println("this is printed");
        }
    }
    public class OtherClass{
        static{
            System.out.println("this is not printed");
        }
    }
    

    JLS 8.7

    A static initializer declared in a class is executed when the class is initialized (§12.4.2). Together with any field initializers for class variables (§8.3.2), static initializers may be used to initialize the class variables of the class.

    请注意,它表示initialized,而不是loaded

    当执行静态成员(方法或变量)或构造函数时,就会发生类初始化。 使用反射访问类的元数据时,这些类不一定要初始化,这取决于通过反射访问的类的内容

    这在JLS 12.4.1中定义:

    A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

    • T is a class and an instance of T is created.
    • T is a class and a static method declared by T is invoked.
    • A static field declared by T is assigned.
    • A static field declared by T is used and the field is not a constant variable (§4.12.4).

    T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.

    A reference to a static field (§8.3.1.1) causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface.

    Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization.

    Spring只需扫描该包中的类,并在这些类中查找注释(如@Component

    如果Spring找到这样的组件,它会创建初始化类的组件的实例


    来自chrylis -cautiouslyoptimistic-的说明:

    Note that in certain special cases (mostly Spring Boot auto-configuration), Spring might not even load the class at all. (It sometimes performs direct bytecode analysis to avoid loading classes that touch optional dependencies.)