2

Possible Duplicate:
How to make spring inject value into a static field

I have below code

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;
  }
}

now i am calling CustomerService.getAllCustomers() from my Action object where getAllCustomers is class level method. I want customerDao to be injected by spring in class CustomerService so that when i call getAllCustomers dependency is available ?

I am using spring decalarative dependency injection

Community
  • 1
  • 1
M Sach
  • 33,416
  • 76
  • 221
  • 314
  • 2
    Why must the DAO be static? It's a simple thing if it's not. I don't see the reason for making it a class variable. – duffymo Dec 11 '12 at 10:23
  • There are a lot of equal questions at stack overflow: search for `[Spring] inject static`! – Ralph Dec 11 '12 at 10:25
  • Having everything static seems a little odd. Do you have a good reason for this? – Qwerky Dec 11 '12 at 10:26

2 Answers2

3

Your design collides head-on with the basic premise of Spring IoC. A static method is nothing more than a singleton method, and the core point of the IoC container is to manage your singletons. You must redesign to use instance methods and fields.

The only way static methods get into the picture is as factory methods, when some complex logic is needed to contribute a singleton to the container.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
0

Do not declare the customerDao field static. Then wire the customer dao into your service class like:

<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>
James
  • 11,654
  • 6
  • 52
  • 81