initializing static field to be available throughout application - java

In one of requirement we have to make available certain attributes through out the web-application so that we can show them in the drop down where ever we want them.So we have few options
We are planning to create a utility class with some static fields which will be assigned values at application startup or when the first request for that list arrived.
Idea is to read a property file and create a List<String> and assign it to the static field so that when ever some one need access to it all he/she need the following call
GeneralUtil.getList()
Since we are working in a web-application one option is to create a listner like
public final class MyListener
implements ServletContextListener {
}
and than read the property file on the contextInitialized method and assign the read value to the static field so that they will be available after startup.
other option is
to create a static block inside GeneralUtil class and place the file read logic inside the static block so that once the class loaded by the cotainer static field will be initialize and we need not to load it for subsequent request.
my question is which of these should be preferred approach and if there is any other best way to achieve this.All i want to avoid to place List in ApplicationContext or any such approach.

I would go with the ServletContextListener approach and an accessor for your property. It seems cleaner and more intuitive than static initializer block.
I would find it also easier if in the future you would like to separate the initialization logic into several methods. In separate class with well defined responsibility it will be easier to do (and to read!) than in some 'GeneralUtil god-like class'.
If you're limited to Servlets I think that's the best and simplest solution.
However, if you're working with EJB's you could as well use #Singleton EJB with #Startup. If you're working with CDI you could use #ApplicationScoped CDI bean.
HTH.

and than read the property file on the contextInitialized method and assign the read value to the static field so that they will be available after startup.
Instead of static variables,place the created List<String> in the servletContext object at contextInitialized(ServletContextEvent sce) method
Note that you could retrieve the servletContext object from ServletContextEvent.

The static solution would mean ThreadLocal and using serialization.
A application scoped bean (yeah, probably best placed in the ApplicationContext) would make the most sense. You could still wrap it in a kind of GeneralUtil wrapper. The solution of Piotr Nowicki is best.
I think you did not want to hear this solution.

Why dont you want to add these values in ApplicationContext ? It makes sense since its going to be same for whole of the application ?
Of the two option you have mentioned its better to load these properties in MyListener instead of static block, reasoning if your load fails your GeneralUtil class wont be loaded unless you specifically catch exception and ignore it, which means application cannot be used.

I've used a ServletContextListener for a similar use case and it worked out just fine. I think this is the easiest and most straightforward solution. Just put the attributes into the ServletContext via setAttribute(name, object) and retrieve them anywhere in your application via getAttribute(name).

Related

reset static field to their initial value using reflexion in java

I use in my project a lib with some class with a lot of static field and other stuffs, who are indirectly updated and consulted at runtime in my app.
I can't update or ignore or mock this class.
How can I re-execute the method who initialise the static field of a class?
I'm currently writing test in my app, which trigger this class.
I want the static field of this class to be at their init state each time I start my app.
The issue is, setting manualy those static field is not possible, it would be too complexe. I need them to be put at their initial state "automaticaly"
I can't change anything to the code of the class, because it's in a lib.
Any idea how I can do that? With reflexion, maybe?
If resetting static fields manually are too complex and classes are stateless, one of the way could be to use custom class loader and reload your classes whenever required.
This article may provide some idea about loading and reloading classes.
You should watch out for performance hit.

Using Springs IoC in this case?

I am curious on the way Spring is able to bind together an application (just in simple terms of course). In a standalone Java application you bootstrap the application with a lookup then Spring instantiates and binds the objects together (DI).
If you for example have a for loop where you don't know the number of iterations (user input) would you use the dependency lookup method inside the loop body? And would you implement the BeanFactoryAware interface in this case? Or do you make the object by using new keyword?
Just an thing that came to my mind while reading.
"Lets pretend that you need a new instance each time"
If you have a component A that has a for loop where you need a new instance of a "bean" B on each iteration, why not just inject a B factory into A and call that within a for loop.
It all really comes down to what makes sense:
If you need to create something simple (e.g. a new String) on each iteration, then there is nothing wrong with using a new keyword.
If it is something more complex, where it is best to encapsulate "creation details", it would not do you any good to depend on any particular framework (e.g. BeanFactoryAware). Just use a builder/factory, which can either be another bean that would be injected, or can be called statically.
Less magic more clarity
If I understood your question correctly the answer could be: Spring beans are singletons by default.
So in most cases you would never need to lookup one inside the for loop - you'll use the instance looked up just before your loop.
Also you're probably trying to think about Spring beans as JavaBeans that you create to populate with data. You could read this link to see the difference: http://www.shaunabram.com/beans-vs-pojos/
Spring beans are more like JavaEE Enterprise Beans, you don't create them - you just use them.

Run method each time a specific annotation is used in a class

Say I have a class with a few fields all marked with a custom annotation. In my case it is #inject, because this is being used for dependency injection. How can I run a method in a separate class each time that annotation is used in my a class? In other words, each time a class is loaded the annotation runs a method that will collect the field data and in turn set the field.
I already have the entire system set up for collecting the resources, but I need some direction on how to actually run that code when the class with #inject annotation is loaded. Is this something that can be done by defining some sort of method in the annotation interface that performs the data collection?
My initial thought is to use a custom class loader, but I don't want to have to set the class loader when I use this jar in other projects. Is there a way to set a custom class loader programmatically for specific classes at runtime? I'm already doing a lot of pre-runtime reflection stuff and i'll already know which classes need to be loaded with a custom loader. Its just a matter of not knowing or if its even possible to set a custom loader on a class from within the code.
Can a classloader even be used to perform tasks such as pre-populating fields, or am I running off on a wrong tangent here? I just need a little direction on the most common way this type of thing is done (pre-populating class fields at runtime).
I was overthinking this problem. You cannot actually run code automatically prior to loading a class (unless its a servlet filter etc). In my situation the answer was to create an instance based on a specific class that already held the resource data I needed. Similar to how Google's Guice does it.
See this question for more insight: How does Guice Populate Annotated Fields
You can use injectors from Google Guice or Spring Framework.

when is a singleton class preferred over a class that has only static methods?

When is a singleton class preferred over a class that has only static methods and a private default constructor?
Please vote.
Use a singleton to better control when initialization occurs. With a static class, any initialization must be at class load-time, which you have little control over. For example, a simple reference to a static final MEMBER will trigger class loading. With a singleton, initialization can trivially be deferred till much later - typically, till first time of use.
Reasons to delay initialization may be:
it's expensive and you don't always need it for that class
you can't initialize till some other resource is initialized (say, a database connection). In this case, a lazily-instantiated singleton often provides correct order of operations without any explicit control - if it's not referenced till after the other resource is initialized, everything happens for free.
Use a singleton to improve testability. If you need to make some kind of mock object (in the broad sense) of the singleton in order to test its clients, one way to do it is to put an interface on its use, and supply a test singleton that's of a different class but implements the same interface.
Using a singleton makes initialization testing easier as well.
Use a singleton when you might need to debug initialization. Stack traces from static initialization can be puzzling. Debugging can be puzzling too. If the class is loaded early, it may break before a breakpoint on the first line in main() is even hit.
When is a singleton class preferred over a class that has only static methods and a private default constructor?
When you need an instance. For example, to pass as method argument.
The main reason for only having static methods is when you just need a toolbox to pack some functions together.
I use singletons for mainly two reasons:
It is really expensive (time or memory) to construct the object, and
I want to only ever do it once.
The data associated with the class
needs to be the same in every instance of the class.
If you have some state you need to store, a singleton is the way to go. For instance, if your class needs to load some configuration from a properties file.
Static method is not dynamic, this is a big different with singleton class instance. So if you need to extends from a class and override some method, the second way won't work.
And the for the second way, you may need to use some static references which may lead to memory leak.
I would say that a singleton class would be preferred only in one case: when you have some configuration to store that is system wide, will rarely (if ever) need to be refreshed.
As an example of what I mean, I have a singleton pattern in one of my applications that represents the NAT device of the user's internet connection. This application is intended for desktop use, and so would rarely (if ever) see a change in the internet connection. Presumably the user could carry their laptop to a new location, and this would change; however, there is a method to recreate the state in this event, but this is very infrequently changed state that can take several seconds to initialize.
This need to keep expensive, infrequently changing, and globally applicable state is best done by either an application scoped bean (my preferred option) or a singleton pattern bean. Static methods aren't as good for preserving this kind of state, though you could also accomplish this using static fields as well to make a pseudo-singleton. (Not sure if there's a better name for this - probably)
In general, my recommendation is not to use singleton like patterns if you can avoid it, as it makes re-use more difficult. If you're using a CDI framework, scope your bean at the application level for easier re-use. (This may not be a concern of yours - if not, you may safely ignore this advice)

Is it possible to use UrlRewriter outside servlet and filter in Java?

I have set up UrlRewriterFilter (Tuckey) with many rules and it is working very good for my servlet. But I want to use the same config to rewrite urls outside servlet - in code that generates e-mails with urls.
So, I need to somehow start UrlRewriter (or some kind of wrapper) to process outgoing url i.e. rewrite them with my outbound-rules already defined in config (urlrewrite.xml).
I would like to use it just like this:
String prettyUrl = urlRewriter.rewriteOutgoingUrl(uglyUrl);
Is this possible at all? How to achieve this goal?
It's open source. You could review it's source code (http://code.google.com/p/urlrewritefilter/source/browse/trunk/src/java/org/tuckey/web/filters/urlrewrite/UrlRewriteFilter.java) and see if the logic is available in standalone class(es) which don't rely on servlet request/response objects. If it is, just use it. Otherwise you can build it yourself based on the original source, reusing as much of the library as possible.
You probably just need to initialize UrlRewriteFilter. Since you have to add this in your web.xml file normally the UrlRewriteFilter config files probably get loaded once. I would try loading this in a static initializer in some wrapper class you define. To define a static initializer all you need to do is within a class have the following:
static {
//Your initialization code goes here
}
This code will only be initialized once, during runtime. For more information please look here:
http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html

Categories