Springboot 手动注入bean

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

/**
 * 手动注入bean
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

  @Autowired
  private static ApplicationContext context;

  /**
   * 获取ApplicationContext
   */
  public static ApplicationContext getApplicationContext() {
    return context;
  }

  /**
   * 插入ApplicationContext
   */
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    context = applicationContext;
  }

  /**
   * 通过name获取 Bean
   */
  public static Object getBean(String name) {
    return getApplicationContext().getBean(name);
  }


  /**
   * 通过class获取Bean.
   */
  public static <T> T getBean(Class<T> clazz) {
    return getApplicationContext().getBean(clazz);
  }

  /**
   * 通过name,以及Clazz返回指定的Bean
   */
  public static <T> T getBean(String name, Class<T> clazz) {
    return getApplicationContext().getBean(name, clazz);
  }
}

 使用

 在new的对象中实现

private final RatePaymentService ratePaymentService = ApplicationContextUtil.getBean(RatePaymentService.class);

 等价于

 

如果你有一个不是Spring Bean的类,通常它不会直接由Spring容器管理并提供依赖注入。然而,如果你想从非Bean注入Spring Service或者其他Bean,可以采用几种间接的方式: 1. **使用`@Autowire`配合构造函数**: 如果这个非Bean类也有构造函数,你可以通过传递`ApplicationContext`实例或者使用`BeanFactory`来获取需要的Service。这允许你在代码中自行创建和初始化bean。 ```java private ApplicationContext context; @Autowired public MyClass(ApplicationContext context) { this.context = context; MyService service = context.getBean(MyService.class); // ... } ``` 2. **手动获取bean**: 直接通过`ApplicationContext`或`BeanFactory`的`getBean()`方法手动获取你需要的服务实例。 ```java private MyService myService; public void init() { myService = context.getBean(MyService.class); } ``` 3. **使用工厂模式**: 创建一个工厂类,作为非Bean的类的一部分,该工厂类可以在内部持有ApplicationContext,并负责创建其他服务对象。 ```java @Service("serviceFactory") public class ServiceFactory { @Autowired private MyService myService; public static MyService createMyService(ApplicationContext context) { return new ServiceFactory(context).getMyService(); } private MyService getMyService() { return myService; } } // 非Bean类中使用 MyService service = ServiceFactory.createMyService(applicationContext); ``` 需要注意的是,这种方式可能会导致一些控制权从Spring容器转移到应用程序代码,减少了Spring的管理和自动化能力。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陌家小染

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值