【问题标题】:how to Inject dependency in static method with spring? [duplicate]如何用spring在静态方法中注入依赖? [复制]
【发布时间】:2012-11-28 21:09:53
【问题描述】:

可能重复:
How to make spring inject value into a static field

我有以下代码

public class CustomerService {

  private static CustomerDAO customerDao;

  public static void getAllCustomers()
  {
    customerDao.getAllCustomers();// here i want 
  }

      public static CustomerDAO getCustomerDao() {
    return customerDao;
  }

  public static void setCustomerDao(CustomerDAO customerDao) {
    CustomerService.customerDao = customerDao;
  }
}

现在我从 getAllCustomers 的 Action 对象调用 CustomerService.getAllCustomers() 是类级别的方法。我希望在 CustomerService 类中由 spring 注入 customerDao 这样当我调用 getAllCustomers 依赖项时可用?

我正在使用spring decalarative依赖注入

【问题讨论】:

  • 为什么 DAO 必须是静态的?如果不是,这是一件简单的事情。我看不出将其设为类变量的原因。
  • 堆栈溢出有很多相等的问题:搜索[Spring] inject static!
  • 让一切都是静态的似乎有点奇怪。你这样做有充分的理由吗?

标签: java spring dependency-injection static-methods


【解决方案1】:

不要声明customerDao字段static。然后将客户 dao 连接到您的服务类中,例如:

<bean id="customerDao" class="com.example.CustomerDao">
    <!-- whatever config you may need here -->
</bean>

<bean id="customerService" class="com.example.CustomerSerivce">
    <property name="" ref="customerDao"/>
</bean>

【讨论】:

  • 无法对非静态字段进行静态引用!
【解决方案2】:

您的设计与 Spring IoC 的基本前提正面冲突。一个static方法无非就是一个单例方法,而IoC容器的核心就是管理你的单例。您必须重新设计以使用实例方法和字段。

static 方法进入图片的唯一方法是作为工厂方法,当需要一些复杂的逻辑来为容器提供单例时。

【讨论】:

    猜你喜欢
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多