I am writing a project with a couple of classses. The main class is a servlet and it makes class to all the other classes. In the init method of the servlet, I load and cache many things into repository-like objects so it doesn't have to instantiate make those objects everytime the servlet is called. Also, the servlet starts when tomcat starts. The problem is many of the classes the servlet calls needs those obejects, so for now, I have been passing the repositores around, but it is getting a little impractical. Some of the constructors are getting too many paramaters because of the objects that need to be passed around.
I was wondering, was there a way to make those objects global? Or some way to allow all classes to acccess those repository objects? I have googled for this, and I don't think there is, but I figured I should ask and make sure.
If caching these objects in repository like objects is the wrong way to load things on init, can you please provide recommendations as to better way to do so?
This was difficult to explain, so if any clarifications are required, I'd be happy to provide them.
Yes, I already took a look at ServletConext. I thought that might not work because there is only one servlet, the main file. The rest of the classes called don't even import the servlet-api.jar.
Can someone tell me if I would be able to use getContext.getAttribute() in a regular class after the object has been bound to the context with the setAttributes method in the main servlet? It would be a shame to do all that work if it wouldn't work, though I will try anyway if no answers.
Well, clearly you can only use getContext().getAttribute("X") in a class with a getContext() method declared. And that would mean you can only realistically call it in a servlet.
But that shouldn't be a problem. Each servlet should be responsible for getting the attributes required and passing them to the objects that need them via parameters. If you have too many parameters, then maybe the problem is that the objects you store in the attributes are too fine-grained and they should be lumped together in some other objects which are easier to pass around.
Yes, we considered abstracting it with a wrapper class, but decided that should be avoided if possible. We already have enough layers of abstraction. At this point though, it seems like we can either leave it as is, or wrap it in a class.