In Springboot, it is sometimes necessary to call your own function, but you cannot use a DAO or service that is hosted on spring.
Most of the information on the Internet is said to add some comments or something, try to not succeed.
Finally, a possible solution was found in a blog post:
Original address: http://blog.csdn.net/xiaoyu411502/article/details/51392281
First create the tool class as follows:
Importorg.springframework.beans.BeansException;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.ApplicationContextAware;Importorg.springframework.stereotype.Component;/*** Normal class calls Spring Bean object: * Description: * 1, this class needs to be placed under the App.java or sub-package to be scanned, otherwise invalid. * @authorAdministrator*/@Component Public classSpringutilImplementsapplicationcontextaware{Private StaticApplicationContext ApplicationContext =NULL; @Override Public voidSetapplicationcontext (ApplicationContext ApplicationContext)throwsbeansexception {if(Springutil.applicationcontext = =NULL) {Springutil.applicationcontext=ApplicationContext; } System.out.println ("---------------------------------------------------------------------"); System.out.println ("---------------------------------------------------------------------"); System.out.println ("---------------com.example.order.util.SpringUtil------------------------------------------------------"); System.out.println ("The ========applicationcontext configuration succeeds in that the normal class can get the ApplicationContext object by calling Springutils.getappcontext (), ApplicationContext = "+springutil.applicationcontext+" ======== "); System.out.println ("---------------------------------------------------------------------"); } //Get ApplicationContext Public StaticApplicationContext Getapplicationcontext () {returnApplicationContext; } //gets the Bean by name. Public StaticObject Getbean (String name) {returnGetapplicationcontext (). Getbean (name); } //Gets the Bean by class. Public Static<T> T Getbean (class<t>clazz) { returnGetapplicationcontext (). Getbean (Clazz); } //returns the specified bean through name, as well as Clazz Public Static<T> T Getbean (String name,class<t>clazz) { returnGetapplicationcontext (). Getbean (name, clazz); }}
Note that the @Component annotations of the above code are required
You can then pass in your own class:
Programtypeservice Programtypeservice = (programtypeservice) springutil.getbean ("Programtypeservice");
So you can get the service.
In this way, after Springboot is started, you can invoke spring's service in your own class.
Calling a service hosted to spring using a common Java class in Springboot