Inject the springBean object into the static method

        When spring starts, it will automatically ignore static members, including the properties and methods, when performing metadata management. If we need to call spring-managed objects in static, we can use the following three methods for injection.

        For example, there is a TestService:

@Service
public class TestService{

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

        1. Use the @PostConstruct annotation

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. Manual management injection

public class TestStatic{

    static TestStatic testStatic;

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

        3. Implement SmartInitializingSingleton

@Component
public class TestStatic implements SmartInitializingSingleton {

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

Guess you like

Origin blog.csdn.net/qq_41061437/article/details/127654505