Multiple Stateless Beans using same static method - java

I came across a problem while working with stateless EJB. I want that a particular static method should be used in that EJB but this method is so important and it has static dependency.
As we know instances of stateless session beans are created as per requirements (one or many). So how can I be sure that all the EJB are using a single copy of that static method. I am not sure but I think every different class who use a static method will load different copy of class and then execute a different copy of the static method.
And I can't rely on singleton EJB as it not guaranty that only one copy will remain because if more than one JVM required by server. Different copy of singleton EJB will be in to existence in different JVM.
Thanks in advance.

Static methods are one per class, even if you create thousands of instance of that class all of them will see just one copy of your static method.
Now as per Spec you should not have static methods in your EJB, you should consider moving this as part of utility if you want it static, or else make it non static.
From the Spec:
EE.5.2.3 Annotations and Injection
As described in the following sections, a field or method of certain
container-managed component classes may be annotated to request that
an entry from the application component’s environment be injected into
the class. Any of the types of resources described in this chapter may
be injected. Injection may also be requested using entries in the
deployment descriptor corresponding to each of these resource types.
The field or method may have any access qualifier (public, private,
etc.). For all classes except application client main classes, the
fields or methods must not be static.

Related

Static factories and dependency injection

In Effective Java (book), static factories are recommended.
On the other hand, keeping dependencies explicit, for example by using DI, is recommended.
But when I want to use a static factory, this explicitness will be skipped, because object instances will be received by calling the static factory method. With static factory methods, I won't have to pass in the object containing the static factory.
How can these two things go together?
Really good question.
Static factories have indeed this drawback (among others): they are not explicit and consequently they cannot be used as switchable dependencies.
I don't think that you can make the two things work together as a static method is associated to the class while the dependency injection is associated to instances.
So it is a choice of design.
Personally, I use the factory method as I don't want to allow to set explicitly the dependency returned by the factory.
It is the case as you want to master the objects creation : consistency, caching, and so for... and you want to provide a clear API.
It is a very straight way to guarantee that.
Setting an object with dependency injection will not provide that.
Generally, I did it for classes that I don't want neither to provide alternative implementations nor to mock during unit tests.
It is the case of business/model classes which I want to master the creation and also for some "utility" classes.
But as soon as the need to explicitly set the dependency happens, I refactor the static factory in something that allows to set the dependency explicitly.
If the master of the objects creation is always necessary, I transform the static factory into an instance factory that I inject.
Otherwise I inject directly the object that was returned by the factory.
There are two sides of the problem:
The object that is being created.
The object that is doing the
creating.
Factories, constructors, and auto-resolving containers are means of changing the way an object can be created (problem 2). That is entirely separate from how an object allows itself to be created (problem 1).
As a general heuristic:
Objects that are being created should be as flexible as possible in terms of how they can be constructed, and should explicitly advertise all their dependencies in their constructors (even if the constructors are made private and a factory is used by creators).
Creators should be as decoupled from the objects they created as your application needs to maintain its flexibility. Highly stable dependencies can be depended on directly. Dependencies that may change or be replaced should not
Differences between static factories, instance factories, constructors, and auto-resolution by container are largely just syntax. The biggest differences are semantic expression (what it communicates to a developer about the structure of the program) and the ability to resolve different implementations at runtime.
To answer your core question, the two things can go together because they are solutions to separate halves of the problem. You can use them both together.

The difference between a scoping annotation and scope instances in Guice

In Guice, when you indicate the lifetime of a certain instance, you will use a scoping annotation like bind(Applebees.class).in(Singleton.class);.
Or you appear to be able to use scope instances like
bind(UserPreferences.class)
.toProvider(UserPreferencesProvider.class)
.in(ServletScopes.REQUEST);
And officially Guice recommends the former approach because the former approach allows us to reuse the Module class.
But I am not sure of the point. My assumption is like this, so please check if this is right.
Scope instances is the term of Servelet, so if you adopt scope instances instead of scoping annotations, the Module class is only applicable to the Servelet. On the other hand, if you use scoping annotations, you can reuse your Module class unless you abandon Guice.
So, is this right? Could you check?
I believe your understanding is correct, but there's a little subtlety about what kind of reuse would be affected.
You're probably referring to this text from the Guice wiki on Scopes (emphasis mine):
The in() clause accepts either a scoping annotation like RequestScoped.class and also Scope instances like ServletScopes.REQUEST:
bind(UserPreferences.class)
.toProvider(UserPreferencesProvider.class)
.in(ServletScopes.REQUEST);
The annotation is preferred because it allows the module to be reused in different types of applications. For example, an #RequestScoped object could be scoped to the HTTP request in a web app and to the RPC when it's in an API server.
Even with Guice's servlet-specific scopes, you can choose between the Scope instance ServletScopes.REQUEST and the #RequestScoped annotation, and choose between in(Scope scope) and in(Class scopeAnnotation) accordingly (see ScopedBindingBuilder). Nearly every scope should have a corresponding annotation, as they are especially useful on classes and #Provides methods.
It's important to realize here that there's always a Scope instance that actually implements the scoping behavior (specifically, wrapping an unscoped Provider so that it can return already-returned instances in the right conditions). To associate an annotation to a Scope instance, you need to make sure that a module calls bindScope, which accepts the Scope annotation class and the Scope instance; for Servlets, Guice has this binding automatically installed via InternalServletModule.
#Override
protected void configure() {
bindScope(RequestScoped.class, REQUEST);
bindScope(SessionScoped.class, SESSION);
// ...
}
So what's the advantage of using in(Class scopeAnnotation)? When binding to a Scope instance, you are telling Guice exactly which Scope instance you want to use, rather than allowing the user an opportunity to use bindScope to bind the annotation to a different Scope instance. In the example I bolded above, you can imagine using the same Module without using the actual Guice servlet extensions (other than the annotations), but this would only be possible if you bind to annotation classes and then call bindScope yourself. If you bind using in(Scope), you'll need to change that line or write a new Module.
This is especially important for your own custom Scope instances and annotations, because it allows you to change your Scoping behavior consistently across your application:
#Override public void configure() {
// BAD: To change the scope, you'll need to change three lines.
// If you don't change all three together, you'll get inconsistent behavior.
bind(A.class).to(AImpl.class).in(MyScope.INSTANCE);
bind(B.class).to(BImpl.class).in(MyScope.INSTANCE);
bindScope(AScoped.class, MyScope.INSTANCE);
}
#Override public void configure() {
// GOOD: To change the scope, you can change one line, and optionally
// extract that line to a separate Module.
bind(A.class).to(AImpl.class).in(AScoped.class);
bind(B.class).to(BImpl.class).in(AScoped.class);
bindScope(AScoped.class, MyScope.INSTANCE);
}

Can a Spring #RequestMapping-annotated method be static?

This is a follow-up question to a previous question.
From what I understand, one #Controller-annotated class with #RequestMapping-annotated methods cannot successfully inherit from another because Spring can't recognize they're both mapping to the same method(s). Even if Spring recognized they were the same instance, it would have no way to decide which instance of the two controller beans to use to invoke the method.
But static methods are invoked independent of any instances of a class, and child classes do not carry their own copy of the parent's static members. Making all of my #RequestMapping-annotated methods static (at least on the parent class) could resolve this problem, which brings us to my question:
Can a public static method be used with #Controller on the class and #RequestMapping on the method? And would it behave about the same as a non-static method*?
* I know that a static method naturally can't access instance members, but controllers should typically be implemented in such a way that there aren't any instance variables anyway. All the methods I'm dealing with would work exactly the same if they were static methods, provided the framework allows for it.
It works fine for me in Spring 3.2.X. Though, controllers often have data members on their instances, but they're usually autowired instances that are services. So I wonder if you're misunderstanding the overall design pattern of the Spring framework.
I can't think of any real benefit in using a static method, the controller instance is already there, so even if you made the controller have all static methods it's still going to get instantiated. I would think the instance invocation overhead would be minuscule and lost in the noise as far as performance.

Java best way to share an object across other objects without using static

I have class A which instantiate class B which in turn do same for class C and so on, forming a large tree. I now need to instantiate an object that should be available all across the tree and I don't want to individually inject this object manually in all classes. I don't want to use a static because there could be different instances of class A running concurrently in different thread and this shared object must be unique per thread. I don't have much experience with thread safe operations.
Use Spring to manage the instance. That way you can inject your instance into any class that needs it and, provided the creation of the parent class is spring managed, the injected bean will be populated.
In some more detail, what you can do is define a class.
public class MyBean {
// Add your class details.
}
And ensure that Spring is either scanning its package or you have defined the bean in your applicationContext.xml file like this. The next stage is to inject this bean where you need to, using the #Autowired annotation..
#Autowired
private MyBean myBean;
And on the creation of that class, myBean will be populated with the same instance of MyBean that was initially created.
Advantages
Doing it this way means that your solution scales well. You can inject it anywhere without constantly changing constructors (and when you're creating more and more sub classes and relationships between classes, this is a prime candidate for Shotgun Surgery.
It's always good to learn about technologies that are used in industry.
Managing a single instance of a class using other methods (like the Singleton pattern) is usually a bad idea.
Disadvantages
Spring does a lot more than just inject objects, and you're pulling down a lot of classes to do just this, which will increase the size of your solution, although not significantly.
Extra Reading
Have a look at a basic Spring tutorial to get you going.
Have a look at the different scopes that you can create beans with, in case some of them suit your needs better.
You either need a local reference in the context that you want to use the object or you need a static reference. Since you don't want to use static you need to get a local reference. You can do this by passing the object in in the constructor or by adding a setter method. Then higher up the tree where ever you construct the child node you pass in the needed object.
You can have kind of a "Parallel Singleton" so to say, i.e. instead of having only one instance it will keep as many instances as there are threads, in a hashmap with a thread-related object being the key.

Static variables restriction in session beans

It's impossible to use static variables on a session bean code. Is this restriction arbitrary or fundamented? And why?
Best regards
As stated in the FAQ on EJB restrictions, one of the restrictions for using EJBs is:
enterprise beans should not read or write nonfinal static fields
Further expanded in the discussion on static fields:
Nonfinal static class fields are disallowed in EJBs because such fields make an enterprise bean difficult or impossible to distribute. Static class fields are shared among all instances of a particular class, but only within a single Java Virtual Machine (JVM). Updating a static class field implies an intent to share the field's value among all instances of the class. But if a class is running in several JVMs simultaneously, only those instances running in the same JVM as the updating instance will have access to the new value. In other words, a nonfinal static class field will behave differently if running in a single JVM, than it will running in multiple JVMs. The EJB container reserves the option of distributing enterprise beans across multiple JVMs (running on the same server, or on any of a cluster of servers). Nonfinal static class fields are disallowed because enterprise bean instances will behave differently depending on whether or not they are distributed.
It is acceptable practice to use static class fields if those fields are marked as final. Since final fields cannot be updated, instances of the enterprise bean can be distributed by the container without concern for those fields' values becoming unsynchronized.
It is fundamental. As per this sun documenation,
Nonfinal static class fields are disallowed in EJBs because such fields make an enterprise bean difficult or impossible to distribute. Static class fields are shared among all instances of a particular class, but only within a single Java Virtual Machine (JVM). *
static means unique for a class OR for all it's objects.
Now, javabeans are supposed to have user-specific data, static fields don't make any sense for these.
One user edits a variable, ant it'll be updated for all other users too. (at free of cost :-)).
However if you want static behaviour for these (i.e. using same data for all users), you have application for that purpose.

Categories