Why does a Spring bean have to be Serializable? [duplicate] - spring

This question already has answers here:
Why Java Beans have to be serializable?
(2 answers)
Difference between JavaBean and Spring bean
(4 answers)
Closed 3 years ago.
PMD spots many Spring components I have, with non-accessable members (no getters or setters), and says the following:
If a class is a bean, or is referenced by a bean directly or
indirectly it needs to be serializable. Member variables need to be
marked as transient, static, or have accessor methods in the class.
Marking variables as transient is the safest and easiest modification.
Accessor methods should follow the Java naming conventions, i.e. for a
variable named foo, getFoo() and setFoo() accessor methods should be
provided.
And I wonder, why does a Spring component/bean has to be Serializable??
Also, is it backed up by Spring documentation (I didn't find...)

I don't remeber having written "all" my Spring components as being Serializable, and I am not sure why they should be.
However, data components that can be stored in a database, and components that can be transported on a network must be. It's part of the trade-off for the Spring style Java Beans to be simple POJOs.
In the older days, JEE Java Beans (aka EJB) had to implement many features in order to be managed by the application container. Spring came along, as a light weight app container and changed all that. Spring manages simple POJOs, so I guess having it serializable is not too bad of a trade off.

Related

Which is better to implement a singleton in a Spring application: a bean or a static field?

I am developing Spring MVC app, i need to implement singleton pattern for some kind of utilities, ex: imageuploader and others.
My question is: in what way to implement singleton for this utilities, to initialize beans for these classes and inject where i need like Controllers, Services, DAO?, or to use static field implementation of singleton to keep instance of this class?
First, try to avoid singleton as it's considered to be a bad practice. Also their interactions with other instances are difficult to test and validate, compared to non-singleton instances.
If you absolutely need it, I'd suggest you use a Spring bean so you can exploit the autowiring mechanism and Spring's bean lifecycle.
See the Beans section of the Spring reference doc for more info.
Using a Spring bean as will allow you to easily inject a mock in unit tests. However, you will only be able to access it from other Spring beans (or objects created by Spring beans that pass in a reference to it).
Also see this discussion in this question: Difference between static class and singleton pattern?
Traditionally, you'd use PropertyPlaceholderConfigurer to inject config from properties files into a Spring web-app. This blog discusses a variety of newer ways to do this with Spring.

Spring vs hibernate object creation

I recently learnt that in hibernate, we need a no-arg constructor in an entity because hibernate instantiates its entities via reflection:
Hibernate implementation. Are we paying the reflection penalty?
I got curious that whether it is the same case with Spring and found that Spring beans do not require a no-argument constructor mandatorily.
This brings me to the question that how does spring creates its objects if not by reflection - to which I think that Spring is a container and instantiates beans and injects dependencies on startup and it must be able to load the application beans via some classloader and hence it does not need reflection.
Then, I get back to the starting point with the question that hibernate also has my application class definition available then why does it need reflection to create its entities?
can somebody please confirm or correct my understanding and provide me an answer?

Scenario when we may be needing #Configurable in spring?

I have question about the need of using #configurable. I have gone through the blog that explains how to use #configurable. But the question that comes to my mind is, what can be the scenario when we need to use #configurable. I can think of two scenarios where it can be useful
In a legacy project, when we are already making any bean with new operator and we want to make it spring managed.
In a new project, we want to enforce that even if developer makes the bean with new operator, still it is spring managed.
Otherwise for new beans we can always declare them in applicationContext.xml and I do not see any need to declare them #configurable.
Please let me know if above understanding is correct or if I am missing something.
UPDATE:- Basically as per my understanding configurable is generally used to inject dependency when creating the object with new operator. But why would i be creating the object with new operator when i am using spring
#Configurable annotation is meant for injecting dependencies in domain-driven applications. That means, in such applications, the domain objects interact with each other to perform a certain operation.
Take the following example:
In an invoicing application, the Invoice class provides a constructor to create it, then it has methods to validate, and finally persist it. Now, to persist the invoice, you need a DAO implementation available within the invoice. This is a dependency you would like to be injected or located. With Spring's #Configurable, whenever an invoice is created using the new operator, the appropriate DAO implementation will get injected and can be used for all persist operations.
I had a more realtime scenario where I used #Configurable annotation as described here.

Spring Instantiation and 'unused beans'

I'm working on a project which means customising an existing application (JasperServer 3.7.1) which is implemented in Spring 2.5.6 (plus a host of other Spring frameworks).
The application consists of a host of applicationContext*.xml containing the bean definitions which when wired together by Spring bring the app to life - I think it's a typical Spring app configuration as although it my first experience using Spring, it seems all quite well put together and follows a lot of the examples I have seen on the web and in books..
Because I'm actually modifying an existing application, changing beans like filterChainProxy (because we have our own security model ,for example) I'm wary of changing the actual config files that come with the product - instead, where possible, I'd prefer to add extra appContext config files to the existing ones which override existing beans (ie leave the original config in tact, as much as possible).
This I've managed to do by creating beans implementing BeanFactoryPostProcessor which on pre-bean initialisation allow me to change the existing property values/bean references to custom ones. This all seems to be working fine.
My query is, say I had a bean with a property that referred to another bean, and my overrider bean changed that reference to my own version of bean, will Spring still instantiate the bean that is no longer referred to ? The reason for asking obviously is that some of these unused beans may be taking up resources, which may be an unwanted overhead.
Thanks in advance
I'm not sure I follow your example, but it might help to clarify a few things.
Generally, Spring will instantiate a bean for every non-abstract bean definition in the context (this is ignoring things like non-singleton bean scopes, but I'll ignore that for the purposes of this explanation). If multiple bean definition files are used, and some bean names are duplicated, then some definitions will be overridden by others. so far, so good, this seems to be what you wanted.
Once the bean definitions have been established, and any duplicated dealt with, then Spring will then instantiate a bean for each of those definitions. If you have changed the definition of BeanA so that it no longer refers to BeanB, but instead refers to BeanC, but the definition of BeanB still exists, then BeanB will still be instantiated, even if it's not being used.
If that example is not representative of your question, then please elaborate.

Plain old singleton or spring singleton bean?

I have a service in my application which is a singleton.
My application is being bloated with the use of spring framework.
I am confused over to use the singleton service as
1: Plain Old Singleton [Access them statically when required]
OR as a
2: Spring singleton bean. [Use DI to inject when required]
Which approach is correct ?
The Spring singleton scope is not the same as the Singleton design pattern, which is not the same as a class with static methods.
From the documentation
"Please be aware that Spring's concept of a singleton bean is quite different from the Singleton pattern as defined in the seminal Gang of Four (GoF) patterns book. The GoF Singleton hardcodes the scope of an object such that one and only one instance of a particular class will ever be created per ClassLoader. The scope of the Spring singleton is best described as per container and per bean. This means that if you define one bean for a particular class in a single Spring container, then the Spring container will create one and only one instance of the class defined by that bean definition."
Also, note you need to be very careful using a Spring singleton as a service that web requests will utilize. Since each request is on its own thread, you can have threading issues if your singleton maintains any state.
To answer your question: Create a class that implements an interface, and use Spring to DI it appropriately. If your service does not maintain state, you can scope it to singleton, otherwise you can scope it to prototype.
I use Spring's beans whenever possible. The framework was designed to manage these things, and it is probably better than me at it. Another reason to use Spring's dependency injection is the possibility to unit-test with mocks instead of the real utility code, thus focusing the unit-test to the exact scope.
EDIT:
To answer the question in the comment, the only case I can think of for a non-bean singleton would be a utility code class, which would contain short pieces of generally reusable code in public static methods. Anything else requires instantiation, and therefore - a bean.

Resources