Tool class
Importorg.springframework.beans.BeansException;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.ApplicationContextAware;Importorg.springframework.stereotype.Component;/*** author:mr.x * DATE:2017/11/8 10:00am * Description:*/@Component Public classSpringcontextutilsImplementsApplicationcontextaware {/*** Context object instance*/ Private StaticApplicationContext ApplicationContext; @Override Public voidSetapplicationcontext (ApplicationContext ApplicationContext)throwsbeansexception { This. ApplicationContext =ApplicationContext; } /*** Get ApplicationContext * *@return */ Public StaticApplicationContext Getapplicationcontext () {returnApplicationContext; } /*** Gets the Bean by name. * * @paramname *@return */ Public StaticObject Getbean (String name) {returnGetapplicationcontext (). Getbean (name); } /*** get beans through class. * * @paramClazz *@param<T> *@return */ Public Static<T> T Getbean (class<t>clazz) { returnGetapplicationcontext (). Getbean (Clazz); } /*** Returns the specified bean by name, and Clazz *@paramname *@paramClazz *@param<T> *@return */ Public Static<T> T Getbean (String name, class<t>clazz) { returnGetapplicationcontext (). Getbean (name, clazz); }}
How to use
Public classArticleformconverter {PrivateArticlerepository articlerepository = (articlerepository) Springcontextutils.getbean (ArticleRepository.class); Publicarticle convert (articleform articleform) {//Update if(Articleform.getid ()! =NULL) {Article article=Articlerepository.findone (Articleform.getid ()); Beanutils.copyproperties (Articleform, article); Article.sethtmlcontent (Processor.process (Article.getcontent ())); returnarticle; } //AddArticle Article =Newarticle (); Beanutils.copyproperties (Articleform, article); Article.sethtmlcontent (Processor.process (Article.getcontent ())); //other property values that require default settings when addedArticle.setreadsize (0); Article.setstatus (ArticleStatus.UP_SHELVES.getCode ()); //Default to ShelvesArticle.setcreatetime (NewDate ()); Article.setuserid (1);//TODO tentatively, should be taken from the session returnarticle; }}
Reference links
The 32nd chapter: How to get the ApplicationContext object of Springboot project: Http://www.jianshu.com/p/3cd2d4e73eb7
To get spring's applicationcontext and Bean objects manually: http://www.cnblogs.com/yangzhilong/p/3949332.html
Transfer from https://www.cnblogs.com/mrx520/p/7802831.html
Springboot how to get other beans such as service, Dao (go) in normal class