SoFunction
Updated on 2025-04-07

Implementation method of calling beans in non-bean classes in springboot

springboot calls bean method in non-bean class

Because when encountering this kind of scene, record an implementation method

Reason for implementation

By providing an implementation through a static method, the corresponding method is called through this implementation

  • Intermediate class
@Component
public class CommonBeanUtil {

    //bean injection    private static MyBean myBean ;


    @Autowired
    public void setMyBean(MyBean myBean) {
          = myBean ;
    }


    /**
      * Get the corresponding yml bean
      *
      */
    public static MyBean getMyBeanInstance() {
        return myBean ;
    }

}
  • Specific beans
@Component
public class MyBean {

    /**
     * 
     */
    public void myFun() {
        \\Code implementation
    }

}
  • Call
@Component
public class MyBean {

    public void fA()
    {
        ()
    }

}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.