springBean オブジェクトを静的メソッドに挿入します。

        Spring が起動すると、メタデータ管理を実行するときに、プロパティやメソッドを含む静的メンバーが自動的に無視されます。Spring 管理のオブジェクトを静的に呼び出す必要がある場合は、次の 3 つのメソッドをインジェクションに使用できます。

        たとえば、次のような TestService があります。

@Service
public class TestService{

    public String test(){
        return "test";
    }
}

        1. @PostConstruct アノテーションを使用する

public class TestStatic{

    @Autowired
    private TestService testService;

    private static TestStatic testStatic;

    /**
    * @PostConstruct该注解被用来修饰一个非静态的void()方法
    *被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行
    *方法执行先后顺序为: Constructor > @Autowired > @PostConstruct
    */
    @PostConstruct
    public void init() {
        testStatic = this;
        testStatic.testService= this.testService;
    }
}

        2. 手動管理インジェクション

public class TestStatic{

    static TestStatic testStatic;

    // 将静态属性以入参的方式传入,然后通过@Autowired注入到spring容器中
    @Autowired
    public void setTestStatic(TestStatic testStatic) {
        TestStatic.testStatic = testStatic;
    }
}

        3. SmartInitializingSingleton を実装する

@Component
public class TestStatic implements SmartInitializingSingleton {

    @Autowired
    private AutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor;
    @Override
    public void afterSingletonsInstantiated() {
        autowiredAnnotationBeanPostProcessor.processInjection(new TestService());
    }
}

おすすめ

転載: blog.csdn.net/qq_41061437/article/details/127654505