1

I have defined HashMap

<bean id="userMap" class="pl.test.pojo.UserMap">
    <property name="userMap">
        <map>
        </map>
    </property>
</bean>

I want to be able to access this content from any class in my project I write to it like:

@Autowired
UserMap userMap;
    Status s = new Status();
    User req = new User();
    s.setStatus(3);
    s.setErrorCode("0");
    s.setErrorDescription("OK");
    s.setCorrelationId(addToQuarantineRequest.getCorrelationId());
    userMap.getUserMap().put(req, s);

and it is ok, but from another class I want to read content of the userMap firstly declaring it with @autowired annotation I have got NullPointerException how can I make Map to be accesible from whole project?

Mithrand1r
  • 2,313
  • 9
  • 37
  • 76

1 Answers1

0

If you want to share among all the objects of your app a Map which is dynamically set, a simple way is to wrap the Map in a bean (like you actually do with the UserMap class) and declare this bean as a singleton. Each time you wire your wrapper class, you shall get the same instance, hence the same Map and be able to share the values. I would do something along:

public interface UserMap {
   void putStatus(User u, Status s);
   Status getStatus(User u);
}

public class UserMapImpl implements UserMap {
   Map<User, Status> statuses = new HashMap<>();

   public void putStatus(User u, Status s) {
      statuses.put(u, s);
   }

   public Status getStatus(User u) {
      statuses.get(u);
   }
}

Then if you are using XML configuration, you declare the bean as a singleton:

<bean id="userMap" class="pl.test.pojo.UserMapImpl" scope="singleton"/>

If you want to initialise the Map with keys/values you can do it in the bean (do you need that?).

And wherever you use this bean, either to put values or read ones, you can declare

public class Foo {
   @Autowired
   UserMap userMap;

   public void someMethod() {
      // put some data into userMap
   }
}

public class Bar {
   @Autowired
   UserMap userMap;

   public void someOtherMethod() {
      // read data from userMap
   }
}
T.Gounelle
  • 5,953
  • 1
  • 22
  • 32