Apache Tomcat: "Context variable" - java

I'm new to Tomcat and hence have a few question. I want to have certain objects available for my Context from any code. I was able to achieve this for a DataSource because that is the example used in the Tomcat guide.
I would like to add 2 additional objects:
Object A that uses this DataSource in the Constructor
Object B that uses Object A in it's constructor
How can I do this?

What's probably the easiest thing to do is use a ContextListener that inserts Objects A and B into the Context. See http://download.oracle.com/javaee/1.4/tutorial/doc/Servlets4.html for a usage example: in the contextInitialized method you can grab the datasource out of the context, create objects A and B and then store them back into the context.

According to the Tomcat 5.5 spec. found on http://tomcat.apache.org/tomcat-5.5-doc/config/globalresources.html I see that Context is not capable of doing such tricks and is not for such usages.
You'd like to have some objects available from "any code". If this any is confined to a single web application, than you can consider #Fermi's answer or maybe you should launch a Spring ApplicationContext. That might sound a bit too difficult if you're not familiar with Spring Framework yet, however if you keep developing your application I think there will be a certain point where things start to become easier if a Spring context already exists from the beginning. (Tell me in a comment if you need help with setting up Spring provided you choose that way.)

Related

Static util class with Spring, unsure if I should make it a SpringBean, design concerns

Quick high level concept of my design..
CLI tool to create AWS EBS snapshots
CLI tool just calls Java class com.util.SnapshotUtil
com.util.Snapshot calls AWS Interfacing class com.aws.AWSAdapter
example usage from command line..
cli-tool create-snapshot.. calls java class eventually calling below method
SnapshotUtil.createSnapshot() // statically call AWSAdapter.createSnapshot();
Currently everything is static and outside of Spring.
Now I am wondering if AWSAdapter should not be static, and loaded by Spring, which would mean my SnapshotUtil would need to create the Adapter through ApplicationContext, I believe, as well as supplying it an XML with the Adapter bean info.
Originally I thought since this is a simple util to deal with ebs snapshots, I could ignore Spring, but the AWSAdapter could potentially be used by other means, however, not sure if being static would be a pro or a con.
The Adapter is designed to only deal with an EBS Snapshot, so its basically either creating / deleting / viewing snapshots by using an AmazonEC2Client instance. Even if a Spring managed class wanted to use this Adapter, my question is if it matters if it loads the Adapter through Spring or just statically call it.
edit in response to answer:
I started turning it into a bean and removed all static references, I gave it a method getInstance() which will load itself through applicationContext and return to caller after initializing other dependencies and configurations. When I call this from outside of spring, is that okay? it seems to be working, is it still considered 'injecting'? I am pretty sure its not injecting, since the caller is not spring managed, but I feel this may be hacky? As in, I am using a spring bean in non spring class, so im never spring managed, so I feel there is no reason to turn the utility into a bean. I am still going to do it because I understand the benefits.
One reason I 'have' to turn it into a bean, is that it uses another spring bean I need to handle authenticating, however I thought about it and I could easily just instantiate the other bean using the 'new' keyword.
Am I correct when I say I turned my class into a bean but it is not 'injected' to callers, at least when using the getInstance() method? if I use the getInstance method() in a spring bean, would there be any difference if I were to 'inject' the utility through spring configurations instead?
Generally, you should favor non-static over static. Regarding your specific example, you should go with Spring beans, because that gives you much more flexibility when you start extending your application/module with more complex features.
For example, very soon static-only classes will require some resources from other parts of the system (and we all know how DI helps here).
Or you will need to advise static invocations with some aspects (be it only simple ones as logging of each request, but think of the more complex cases like transactions). With Spring beans this is very simple to achieve and, very important, simple to add afterwards without a big re-engineering and re-testing.
Also, you will much easier integrate beans with other Spring APIs and frameworks that are already well integrated with Spring. For example, you will easy use your bean in an Apache Camel route.
These are just a few points that came to my mind, there are many more of them. But, as always, consider all the pros and cons and pick the right tool for the job.
Edited part of the question
"When I call this from outside of spring, is that okay?"
Yes, it's fine to obtain the bean instance from the Spring application context directly in a class that is not managed by Spring or when the bean name is not known until runtime. In my example with Apache Camel route, that's exactly what Camel does. :)
"Am I correct when I say I turned my class into a bean but it is not 'injected' to callers, at least when using the getInstance() method?"
Yes, it is still a bean with all of the bean's functionality (with other beans injected in it, with aspects around it, etc).
"If I use the getInstance method() in a spring bean, would there be any difference if I were to 'inject' the utility through spring configurations instead?"
Regarding this, you may take a look at this question and at the article written by Martin Fowler, which is also referenced from the question.
In my opinion, you should not do it, it is less readable and quite unnecessary. Injecting the resources as fields is a type safe and a clean mechanism for a class to declare its dependent resources.
Also, bean lookup may be costly if executed frequently. I experienced this on a project I worked on in the past. I don't know why, but it takes some time for Spring (at least the Spring version we used then) to look up and return the bean, and it is noticeable if executed in a loop.

Tomcat keep webapp api running

I'm trying to create a web application for tomcat 7, but my problem is that I want to keep the whole backbone of the application running, so that my servlets can call the functions. Ex. I have my com.example.Main class which house all the instances to things like User managers and such. But instead of getting the main instance redefined on each servlet call, It would get defined once for all the servlets to use.
Best Regards,
- Roe
As far as I understand, you want a singleton. Check this answer for implementation.
But note that singletons are "evil". A more webapp approach is to not have it as singleton, but initialize it once in a ContextLoaderListener and then put it as a ServletContext attribute. Then each servlet can obtain it by getting it from the servlet context.
I agree with Bozho - you seem to be talking about a Singleton and I share his reservations about using them.
If you do implement it as a singleton, or use Bozho's suggested solution, it is important for you to understand that there will be only one instance of the class, potentially being used by many servlets at the same time. As a result, it is your responsibility to make sure that the class is thread safe, or your application will produce unreliable results.

Better way of distributing objects/classes inside a project

I have some Classes like Clipboard or ProcessRegister that I only want to run once in my Project, so only one instance.
My Question in now: How do I distribute those instances best in my Project.
ATM both are singleton and object they use the get an instance over the getInstance().
Another Idea of mine is to create a class Project, that has some static methods like getProjectClipboard()or getProcessRegister()that return the instances.
What is the best way to distribute them? Are there any patterns for that?
Greetings Dennis
There are mainly two patterns that can be used: the service locator, and dependency injection. The service locator pattern is probably the one you are referring to, where everywhere you look for a reference for these objects you explicitly retrieve it from a central location, which for simple java applications is usually a bunch of static methods. this is OK, and I don't think there is an overall better approach here, just make sure that you have only one static method for each singleton, and that you call it always.
Then a few years ago, a shift of mentality became mainstream, dependency injection, and its more popular framework... Spring, with this paradigm, in each place you need to access this singletons, you don't specify where they are, but your object get the correct references injected...
I would recommend you to look into dependency injection... and probably Spring, as it is the mainstream solution for it... I think that giving you more insgight into Spring is out of the scope of the question, but there is A LOT of documentation in Internet if you search for Spring tutorials or something similar...
Basically what you would do is create as spring beans each of your singletons, and then have spring injecting them into your objects... The caveat to this approach is that all of your objects have to be built by Spring, but in practice it doesn't suppose any disadvantage, it will actually make your life easier in terms of testings, maintenance...
Singletons, when done at language level, are global objects. This may work for small projects but is not the best idea when the project grows. There may evolve a situation where suddenly a singleton is only a singleton relative to a certain scope. Then you have to touch the object and every access to it.
That said if you have a Project object or an Application object these are good places to have accessors to Project-relative singletons. If Project is just a class that provides a lot of static accessors it is like a namespace. It is a win in clarity and will make refactoring easier but it doesn't change much in terms of architecture.
Best way to do singletons is not on language level but on application level. Very helpful are application and dependency frameworks like Spring (where the standard scope for beans is in fact singleton). If you later on see that the object isn't singleton you just change the configuration - but not the object itself.
As someone who is usually against the usage of stateful singletons (except for caching purposes), I would say: have one instance of these classes per running application and inject them where you need them (see Dependency Injection). That will also allow you to run the same application multiple times with different configuration in the same JVM.

Guice: Scope related questions

I'd like to use a dependency injection framework.
During my evaluation I came to the conclusion that Google Guice seems to fit best for my demands.
However, some questions came into my mind:
Imagine a web application in which a user can have independent windows within a http session. The Session scope is too general while the Request scope is too narrow for me. Is there a scope which will help me out? (something I would call "window" or "controller instance" scope)
Are there any pitfalls writing a custom scope?
Our web application and several stand alone console applications are using the same classes. I am facing the problem that the scope of a class depends on the application type which is only known at runtime.
E.g. in a standalone application the scope would be "No-Scope" or "per-Thread Scope", while in a web application it would be bound to a Session/"window".
How to solve this problem?
You'll have to create a custom scope
Not that I know. We've been using a custom scope and it works very well.
Have a different implementations of the custom scope being used in the web application and other for the standalone application
To answer 3. use different modules for your versions, and set the scopes there.
bind(Grill.class).to(Applebees.class).in(Scopes.SINGLETON);
You can use scope with application context handlers which help in deciding how your scoping logic works. Then using the same custom scope you can control how the objects get created at runtime.

Proper ApplicationContext usage?

I've recently started learning the Spring Framework, and I'm a bit unclear on how the ApplicationContext is supposed to be used - in both standalone and web applications. I understand that the ApplicationContext, once instantiated with the spring configuration xml, is the "spring container" and is a singleton.
But:
In the starting point - main method - of an app do I use ApplicationContext.getBean("className") and then rely on DI for all other registered beans or is there a way to use only DI?
Is there any other place besides the main method where I could/should use ApplicationContext.getBean("className")?
If and when should ApplicationContext.getBean("className") be used in a web app?
If in your opinion there is information I MUST know regarding DI related to web applications, even though I may not of specifically inquired about it, please share.
You need at least one call into the context from outside it, there's no avoiding that. With webapps, that part is hidden from you, and it it feels like everything is using DI, even though Spring's servlet glue code is doing some unpleasantness behind the scenes.
Could, yes; should, no. There are very few good reasons for calling getBean yourself.
The most obvious scenario is when you have a servlet filter that needs access to the context. FIlters aren't managed by Spring, and so cannot have stuff wired into them by Spring.
That's a bit too vague. Read the reference docs :)
I generally recommend only one usage of ApplicationContext.getBean() per application, and rely on the Spring configs to do the rest.
The exception applies in unit tests, where I want to load up a particular subset of beans (so I would explicitly load a bean that normally would be loaded from the top of my bean hierarchy).

Categories