-1

I have the service MyStaticService which is doing some calculations using a DAO. How can I inject the MyDao object into the class field? I've tried to implement the setter with @Autowired but when I call doCalculations(..) the DAO is null. What am I doing wrong?

 public class MyStaticService
     {
        private static MyDao dao;

        public static int doCalculations(..){
         dao.doSmth()
         // omitted
       }
    }
Neuron
  • 5,141
  • 5
  • 38
  • 59
CameronCoob
  • 81
  • 1
  • 11
  • First, don't use this pattern. Second, if you're going to use it, make sure you initialize your context, and therefore initialize the field, before trying to invoke the method. – Savior Mar 26 '18 at 17:54

2 Answers2

1

First of all you cannot Autowire Spring beans inside classes that are not managed by Spring.

Hence in your example even if you DAO is a valid Spring managed bean, you cannot inject that in your MyStaticService. Of course it will always be null. Spring wouldn't be able to know what dependencies to scan and inject if your static service class is itself not a Spring Component

Spring dependency injection is meant to work only in classes managed by the Spring IOC container.

Your StaticService class makes more sense to be of a Singleton Class, hence there is no harm in declaring it as a Spring component.

@Component
public class MyStaticService

Then you can Autowire your DAO classes.

Service classes should ideally be Singletons with other singletons dependencies like your DAOs.

bitscanbyte
  • 650
  • 8
  • 14
-1

You need initialize your object for you to access the functions of MyDao() class like this:

    dao = new MyDao();

or while you create the instance

    private static MyDao dao = new MyDao();

else it will always show null

TheFlyBiker 420
  • 69
  • 1
  • 13