0

I'm building an online chat application in spring just like the one on Facebook. I want to create a bean with a property[Array] called active-users. Then performs the following:

  1. Whenever a user logs in, I'll add his/her userId into the array.
  2. When an other user logs in, I'll display the users that are currently online.

How do I create a bean which is available at all times?

For Ex : In servlets, this can be achieved by using the Servlet context :

ServletContext context = request.getServletContext();
context.setAttribute("userId", "123");
CBroe
  • 91,630
  • 14
  • 92
  • 150
Ajay Ullal
  • 378
  • 2
  • 10

2 Answers2

0

All beans in Spring are singletons by default, they will be alive during the whole application's lifecycle unless you'll do something with the spring context.

So just create a spring bean and declare a global list in it. You can access it anywhere where the spring bean will be injected from the current context.

Paulius Matulionis
  • 23,085
  • 22
  • 103
  • 143
0

It's simpler with Spring than in a pure servlet application, because all beans declared in root application context reside in fact automatically in the ServletContext and as such are unique in the application. And Spring can natively inject them in any controller or service bean to allow you to use them at will.

The only limit, is that they are unique per instance, so it won't be enough it you had a farm of servers for your application.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252