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.
Related
Component and Service type beans and most of the other bean types are by default singleton.
In one of my code Pull requests, I declared a method as static in a Component as the method wasn't modifying any class level variables.
My code reviewer pointed out that since the class is anyways a Singleton and is going to have a single reference, he said it was unnecessary to make the method static, but rather make it a instance method.
Which way is the correct way of writing code as most of the classes in my application are Singletons?
Your reviewer is probably right about this one, it makes little sense to declare a static method inside a singleton; unless this static method is a factory method that returns the singleton instance itself.
I could think of two other reasons not to declare static methods in the singleton : testing is harder for static methods in some cases and you will really confuse the caller of this singleton. He/she might see that there is a static method and have a hard time understanding why it was declared like this, it would require extra reasoning as far as I see for such a method.
I have following scenario, and a confusion to have instance method or static method for dbhelper?
We have a dbhelper class which as name suggest help other classes to work with MySql db.
The db helper class will be used by 2 independent module.
Java Webapp.
Windows based Java app
Currently all the methods in dbhelper class are instance methods
There are 8 methods in dbhelper class among which 3 will be common for webapp and windows app and rest only used by webapp.
Windows app is kind of continuously running 24*7.
Our confusion is such that if we keep methods as instance methods, then we have to crate object of dbhelper class and eventually will be always alive as used by windows app.
What I see advantage of keeping methods as static is no object required.
Note:
I know how static and instance method works.
Google search do not help for this specific example.
The question is too broad for a specific answer. But I can answer with the kinds of things I'd be thinking about, in general.
First of all, if your static methods are going to save state in static class variables, that's not good practice. If there's any state involved, you definitely want to make them instance methods, so that an object of that instance will be holding the state.
You mention that your methods are there to help work with a database. How are they going to access the database? If the database isn't passed as one of the method parameters, then that means the reference to the database has to be stored somewhere, and I think it's best if the dbhelper is an instance that stores a reference to the database (or a reference to some other object that can be used to retrieve the database object) as one of the instance fields.
So I'm going to assume that the methods take a database parameter, or a parameter to some other object that will give you the database object. Given that, there are two things I'd think about when considering whether to make your methods static.
(1) What is the likelihood that the method will change because the requirements change? If it's at all likely, then I'd definitely lean toward making the methods instance methods; in fact, I'd consider making "dbhelper" an abstract class or interface, and having different implementation classes implement the abstract methods in different ways when something changes. That seems to me to be more flexible than just having one static class whose code has to change if the business logic changes. It lets you switch back and forth, or even lets you switch the logic dynamically at run time.
(2) Will you want to mock the method for testing? If your methods access a database, then you will probably want to provide a mock version of the method when unit-testing other classes that call the method, since you want to be able to test them without worrying about setting up the database access and everything. This would also argue for making dbhelper abstract or interface, so that you can provide a mock implementation in addition to your real implementation. (However, some testing platforms like JMockit will let you mock static methods.)
Those are the kinds of things that would lead me toward making the methods instance methods. If you're sure that they don't apply, then it should be OK to make them static methods.
Instead of using static, make use of Singleton design approach for dbHelper class.
something like this,
public class MyDBHelper {
private static MyDBHelper instance;
private MyDBHelper(){}
public static MyDBHelper getInstance(){
if(instance == null){
instance = new MyDBHelper();
}
return instance;
}
public void addRow() {
........
}
}
From other classes, you can access the methods like below
MyDBHelper.getInstance().addRow();
1st : Make all methods of class dbhelpe static and load them when your application gets loaded by any web/application server.This task can be accomplished by static block .
2nd : try to implement Singleton pattern on your dbhelp class ,so that only one object of your class can be shared,this will not leads your application to create object many times,and your application will work faster.
First of all, methods in one class used by multiple callers (web app and Windows app) suggests violation of SRP, so you should be dividing the single DB helper into multiple classes.
Secondly, there are advantages and disadvantages of static and instance methods.
If you practice TDD or DI, it discourages static methods as they are non-mockable (unless you use a framework like Powermock which to me seems a bit hacky.)
If you only do end to end testing, its okay to use static methods.
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.
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.
I have never found good answers to these simple questions about helper/utility classes:
Why would I create a singleton (stateless) instead of using static methods?
Why would an object instance be needed if an object has no state?
Often, singletons are used to introduce some kind of global state to an application. (More often than really necessary, to be honest, but that's a topic for another time.)
However, there are a few corner cases where even a stateless singleton can be useful:
You expect to extend it with state in the foreseeable future.
You need an object instance for some particular technical reason. Example: Synchonization objects for the C# lock or the Java synchronized statement.
You need inheritance, i.e., you want to be able to easily replace your singleton with another one using the same interface but a different implementation.Example: The Toolkit.getDefaultToolkit() method in Java will return a singleton whose exact type is system dependent.
You want reference equality for a sentinel value.Example: DBNull.Value in C#.
I could see a case for a stateless singleton being used instead of a static methods class, namely for Dependency Injection.
If you have a helper class of utility functions that you're using directly, it creates a hidden dependency; you have no control over who can use it, or where. Injecting that same helper class via a stateless singleton instance lets you control where and how it's being used, and replace it / mock it / etc. when you need to.
Making it a singleton instance simply ensures that you're not allocating any more objects of the type than necessary (since you only ever need one).
Actually i've found another answer not mentionned here: static methods are harder to test.
It seems most test frameworks work great for mocking instance methods but many of them no not handle in a decent way the mock of static methods.
In most programming languages classes elude a lot of the type system. While a class, with its static methods and variables is an object, it very often cannot implement an interface or extend other classes. For that reason, it cannot be used in a polymorphic manner, since it cannot be the subtype of another type. For example, if you have an interface IFooable, that is required by several method signatures of other classes, the class object StaticFoo cannot be used in place of IFooable, whereas FooSingleton.getInstance() can (assuming, FooSingleton implements IFooable).
Please note, that, as I commented on Heinzi's answer, a singleton is a pattern to control instantiation. It replaces new Class() with Class.getInstance(), which gives the author of Class more control over instances, which he can use to prevent the creation of unneccessary instances. The singleton is just a very special case of the factory pattern and should be treated as such. Common use makes it rather the special case of global registries, which often ends up bad, because global registries should not be used just willy-nilly.
If you plan to provide global helper functions, then static methods will work just fine. The class will not act as class, but rather just as a namespace. I suggest, you preserve high cohesion, or you might end up with weirdest coupling issues.
greetz
back2dos
There is a trade-off between using which one. Singletons may or may not have state and they refer to objects. If they are not keeping state and only used for global access, then static is better as these methods will be faster. But if you want to utilize objects and OOP concepts (Inheritance polymorphism), then singleton is better.
Consider an example: java.lang.Runtime is a singleton class in java. This class allows different implementations for each JVM. The implementation is single per JVM. If this class would have been static, we cannot pass different implementations based on JVM.
I found this link really helpful: http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html?
Hope it helps!!
Singleton is not stateless, it holds the global state.
Some reasons which I can think of using Singleton are:
To avoid memory leaks
To provide the same state for all modules in an application e.g database connection
For me "Want Object State use Singleton, Want Function use static method"
It depends on what you want. Whenever you want the object state (e.g. Polymorphism like Null state instead of null, or default state), singleton is the appropriate choice for you whereas the static method use when you need function (Receive inputs then return an output).
I recommend for the singleton case, it should be always the same state after it is instantiated. It should neither be clonable, nor receive any value to set into (except static configuration from the file e.g. properties file in java).
P.S. The performance between these 2 are different in milliseconds, so focus on Architecture first.
According to GoF’s book Design Patterns, chapter ‘Singleton’, class operations have the following drawbacks compared to singletons (bold emphasis mine):
More flexible than class operations. Another way to package singleton’s functionality is to use class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance of a class. Moreover, static member functions in C++ are never virtual, so subclasses can’t override them polymorphically.