SpringBoot静态方法获取 bean的三种方式

本文介绍SpringBoot中通过不同方法获取Bean实例的技术细节,包括使用@PostConstruct注解、启动类ApplicationContext以及手动注入ApplicationContext等三种方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意: 调用者要被spring管理

目录

方式一  注解@PostConstruct

方式二  启动类ApplicationContext

方式三 手动注入ApplicationContext


方式一  注解@PostConstruct

import com.example.javautilsproject.service.AutoMethodDemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * springboot静态方法获取 bean 的三种方式(一)
 * @author: clx
 * @date: 2019/7/23
 * @version: 1.1.0
 */
@Component
public class StaticMethodGetBean_1 {

    @Autowired
    private AutoMethodDemoService autoMethodDemoService;

    @Autowired
    private static AutoMethodDemoService staticAutoMethodDemoService;

    @PostConstruct
    public void init() {
        staticAutoMethodDemoService = autoMethodDemoService;
    }

    public static String getAuthorizer() {
        return staticAutoMethodDemoService.test();
    }
}

注解@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
 * @date: 2019/7/23
 * @version: 1.1.0
 */
@SpringBootApplication
public class Application {
    public static ConfigurableApplicationContext ac;
    public static void main(String[] args) {
       ac = SpringApplication.run(Application.class, args);
    }

}

调用方式


/**
 * @author: clx
 * @date: 2019/7/23
 * @version: 1.1.0
 */
@RestController
public class TestController {
    /**
     * 方式二
     */
    @GetMapping("test2")
    public void method_2() {
        AutoMethodDemoService methodDemoService = Application.ac.getBean(AutoMethodDemoService.class);
        String test2 = methodDemoService.test2();
        System.out.println(test2);
    }
}

方式三 手动注入ApplicationContext

手动注入ApplicationContext


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


/**
 * springboot静态方法获取 bean 的三种方式(三)
 * @author: clx
 * @date: 2019/7/23
 * @version: 1.1.0
 */
@Component
public 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;
    }
}

调用方式


    /**
     * 方式三
     */
    @Test
    public void method_3() {
        AutoMethodDemoService autoMethodDemoService = StaticMethodGetBean_3.getBean(AutoMethodDemoService.class);
        String test3 = autoMethodDemoService.test3();
        System.out.println(test3);
    }

以上三种方式楼主都测试过可以为完美使用

Spring Boot应用程序中,获取Bean有多种方式。通常我们会依赖于Spring的上下文管理自动装配所需的组件,但在某些场景下也需要手动去取得某个特定的Bean实例。 ### 方式一:通过@Autowired注解 这是最常见的方式之一,在需要注入的地方直接使用`@Autowired`注解,并声明你要注入的对象类型即可让Spring自动为你找到并赋值相应的bean。 ```java @Service public class MyService { @Autowired private AnotherBean anotherBean; } ``` ### 方式二:利用构造函数或者Setter方法注入(@Inject/@Autowired) 除了字段级别的注入外,还可以选择将依赖项作为构造参数传入,或者是提供setter方法来设置依赖属性。这种方式有助于提高单元测试时的灵活性以及更清晰地表达出类之间的依赖关系。 #### 构造器注入示例: ```java @RestController public class MyController { private final AnotherBean bean; // 使用构造器注入另一个bean public MyController(AnotherBean bean) { this.bean = bean; } } ``` #### Setter方法注入示例: ```java @Component public class MyClass{ private Helper helper; @Autowired public void setHelper(Helper helper){ this.helper=helper; } } ``` ### 方式三:ApplicationContextAware 接口 如果是在非受管环境中想要访问到spring容器里的beans的话,则可以考虑实现 `org.springframework.context.ApplicationContextAware` 接口。这允许我们在任意地方获得整个application context 并从中检索指定名称的 Bean。 ```java import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component("myAppCtx") public class ApplicationContextProvider implements ApplicationContextAware { private static ApplicationContext ctx = null; public static ApplicationContext getApplicationContext() { return ctx; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ctx = applicationContext; } } // 获取名为 "anotherBean" 的bean 示例: MyClass.anotherBeanInstance = (AnotherBean) ApplicationContextProvider.getApplicationContext().getBean("anotherBean"); ``` ### 方式四:从配置文件加载静态资源或者其他复杂类型的Beans 对于一些比较特殊的场景比如读取外部properties/json/yaml等格式的数据源生成对应的Bean对象,我们一般会采用工厂模式结合@Configuration + @Bean定义的方式来完成。 ```java @Configuration class AppConfig { @Value("${api.url}") String apiUrl; @Bean(name="httpClientConfiguredWithApiUrl") HttpClient createHttpClient(){ return HttpClient.createDefault(apiUrl); } } ``` 以上就是几种常见的在Spring Boot应用里获取、创建和注册Bean的方法了!
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值