您好,欢迎访问一九零五行业门户网

Spring Boot获取bean的方式有哪些

在使用spring框架中我们都知道,某个类如果使用了@service、@autowire 这种依赖注入的方式引用了其他对象,在另外一个类中,只有通过spring的ioc容重中获取这个类的实例时,那些被依赖的对象才能正确被初始化,否则那些被依赖的对象都是null。 
所以就有一个问题,在普通类中如何获取spring ioc容器中的bean(spring托管的bean)。
我们都知道,在spring中applicationcontext这个上下文对象是获取bean的基础。
在spring boot中,我们可以通过下面的三种方式来获取bean。
方式一 注解@postconstruct
postconstruct 注释用于在依赖关系注入完成之后需要执行的方法上,以执行任何初始化。此方法必须在将类放入服务之前调用。
支持依赖关系注入的所有类都必须支持此注释。即使类没有请求注入任何资源,用 postconstruct 注释的方法也必须被调用。只有一个方法可以用此注释进行注释。
应用 postconstruct 注释的方法必须遵守以下所有标准:
该方法不得有任何参数,除非是在 ejb 拦截器 (interceptor) 的情况下,根据 ejb 规范的定义,在这种情况下它将带有一个 invocationcontext 对象 ;
该方法的返回类型必须为 void;
该方法不得抛出已检查异常;
应用 postconstruct 的方法可以是 public、protected、package private 或 private;
除了应用程序客户端之外,该方法不能是 static;
该方法可以是 final;
如果该方法抛出未检查异常,那么不得将类放入服务中,除非是能够处理异常并可从中恢复的 ejb。
方式二 启动类applicationcontext实现方式:在springboot的启动类中,定义static变量applicationcontext,利用容器的getbean方法获得依赖对象。
import org.springframework.boot.springapplication;import org.springframework.boot.autoconfigure.springbootapplication;import org.springframework.context.configurableapplicationcontext;/** * @author: clx * @version: 1.1.0 */@springbootapplicationpublic class application { public static configurableapplicationcontext ac; public static void main(string[] args) { ac = springapplication.run(application.class, args); } }
调用方式
/** * @author: clx * @version: 1.1.0 */@restcontrollerpublic class testcontroller { /** * 方式二 */ @getmapping("test2") public void method_2() { automethoddemoservice methoddemoservice = application.ac.getbean(automethoddemoservice.class); string test2 = methoddemoservice.test2(); system.out.println(test2); }}
方式三 手动注入applicationcontextimport org.springframework.beans.beansexception;import org.springframework.context.applicationcontext;import org.springframework.context.applicationcontextaware;import org.springframework.stereotype.component; /** * springboot静态方法获取 bean 的三种方式(三) * @author: clx * @version: 1.1.0 */@componentpublic class staticmethodgetbean_3<t> implements applicationcontextaware { private static applicationcontext applicationcontext; @override public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception { staticmethodgetbean_3.applicationcontext = applicationcontext; } public static <t> t getbean(class<t> clazz) { return applicationcontext != null?applicationcontext.getbean(clazz):null; }}
调用方式
/** * 方式三 */@testpublic void method_3() { automethoddemoservice automethoddemoservice = staticmethodgetbean_3.getbean(automethoddemoservice.class); string test3 = automethoddemoservice.test3(); system.out.println(test3);}
以上就是spring boot获取bean的方式有哪些的详细内容。
其它类似信息

推荐信息