Introduce spring-managed classes in non-spring-managed packages, and you can use a class to inherit Applicationcontextaware.
In two categories, the first of which is under Spring's packet scanning range:
package Com.iwhere.test.util;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Org.springframework.beans.beansexception;import Org.springframework.context.applicationcontext;import Org.springframework.context.applicationcontextaware;import org.springframework.stereotype.Component;/** * Introduce the Bean in spring in the normal class, under the scan package of Springboot * @ServletComponentScan * * If not under Springboot package scan, you do not need component, but need to App.ja Introduced in VA * @Import (value={springapputils.class}) * * @author 231 * @time March 15, 2017 pm 2:40:32*/@Component public classSpringapputils implements Applicationcontextaware {Private StaticLogger Logger = Loggerfactory.getlogger (springapputils.class); Private StaticApplicationContext applicationcontext; @Override public voidSetapplicationcontext (applicationcontext Context) throws beansexception {if(springapputils.applicationcontext = =NULL) {applicationcontext=context; } logger.info ("Springapputils is init"); } /** * Get ApplicationContext * * @return*/ public StaticApplicationContext getapplicationcontext () {returnapplicationcontext; } /** * by getting beans then*/ public StaticObject Getbean (String Name) {returngetapplicationcontext (). Getbean (name); } /** * Get beans from class*/ public Static<T> T Getbean (class<t>Clazz) { returngetapplicationcontext (). Getbean (clazz); } /** * Get beans by name and class*/ public Static<T> T Getbean (String name, class<t>Clazz) { returngetapplicationcontext (). Getbean (name, clazz); }}
The second type: the configuration class is not under the Springboot scan:
There is no need to add @component annotations to the class at this time
But it needs to be introduced in App.java.
@Import (value={springapputils.class})
@SpringBootApplication @servletcomponentscan@import (value={springutil. Class}) publicclass App { {main}}
springboot-9-introducing beans in Non-springboot managed classes