Spring MVC - using FactoryBeans - spring

A bean that implements the interface FactoryBean (a pattern to encapsulate interesting object construction logic in a class)
can be used as a normal bean?

To summarize in short:
Yes you can use a FactoryBean like a normal bean (inject it into other beans for example)
Additionally the factory bean will create instances (or a singleton instance) of <T> on demand, which will be a Spring bean as well. Thus you could also inject an instance of <T> into other beans. Spring will create an instance using your factory in this case
The main reason for using custom FactoryBeans from the reference documentation:
The FactoryBean interface is a point of pluggability into the Spring IoC container’s instantiation logic. If you have complex initialization code that is better expressed in Java as opposed to a (potentially) verbose amount of XML, you can create your own FactoryBean, write the complex initialization inside that class, and then plug your custom FactoryBean into the container.
Furhter reading: http://docs.spring.io/spring/docs/4.1.7.RELEASE/spring-framework-reference/html/beans.html#beans-factory-extension-factorybean

A FactoryBean is defined in a bean style, but the object exposed for bean reference (getObject()) is always the object that it creates

Related

Spring how to enforce use of bean factory, for prototype beans with runtime arguments

In my spring-boot application i have "normal" singleton beans that "autowire" the stuff they need via a private constructor. So it is not possible to call "new" anywhere in the code.
But i also have "prototype" beans that need runtime arguments to be created. To create such beans i could use this approach (lazy instantiated protype beans): Spring bean with runtime constructor arguments
The problem is that the constructor is used and hence must be "visible". Is there any way in Spring to create such prototype beans with a private constructor? I want to enforce the usage of BeanFactory to create them.
You can try to build your prototype beans with an implementation of
factoryBean,public interface FactoryBean<T> {
T getObject() throws Exception;
Class<T> getObjectType();
boolean isSingleton();
}
So you can encapsulate more complexe logic inside,
A full exemple here

Difference between beanFactoryPostProcessor and postProcessBeforeInitialization [duplicate]

I was trying to understand the difference between BeanFactoryPostProcessor and BeanPostProcessor.
I understood that BeanFactoryPostProcessor operates on bean definition i.e. before the bean instance is getting created it gets executed and BeanPostProcessor gets executed after bean is instantiated and lifecycle events are called.
Does this mean BeanFactoryPostProcessor is not a part of spring lifecycle events as it's called before instantiation while BeanPostProcessor is the part of Spring lifecycle events? Kindly verify if my understanding is right.
BeanFactoryPostProcessor is an interface and beans that implement it are actually beans that undergo the Spring lifecycle (Example below) but these beans don't take part of the other declared beans' lifecycle.
public class CustomBeanFactory implements BeanFactoryPostProcessor {
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
for (String beanName : beanFactory.getBeanDefinitionNames()) {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
// Manipulate the beanDefiniton or whatever you need to do
}
}
}
The differences about BeanFactoryPostProcessor and BeanPostProcessor:
A bean implementing BeanFactoryPostProcessor is called when all bean definitions will have been loaded, but no beans will have been instantiated yet. This allows for overriding or adding properties even to eager-initializing beans. This will let you have access to all the beans that you have defined in XML or that are annotated (scanned via component-scan).
A bean implementing BeanPostProcessor operate on bean (or object) instances which means that when the Spring IoC container instantiates a bean instance then BeanPostProcessor interfaces do their work.
BeanFactoryPostProcessor implementations are "called" during startup of the Spring context after all bean definitions will have been loaded while BeanPostProcessor are "called" when the Spring IoC container instantiates a bean (i.e. during the startup for all the singleton and on demand for the proptotypes one)
Here is a flow diagram that might help to understand the spring bean initialisation life cycle.
As we can see, the implementation of theBeanFactoryPostProcessor is executed before any spring bean instantiation, contrary to the BeanPostprocessor, where the implemented method will be executed only when the bean is instantiated.
The source image is from the Spring 5 Design Patterns Book.
I pick the explanation from the book:
After loading the bean definitions from all styles of configurations,
BeanFactoryPostProcessor comes into the picture to modify the
definition of some beans, and then the container instantiates the
beans. Finally, BeanPostProcessor works on the beans, and it can
modify and change the bean object. This is the initialization phase.
Bean Factory Post Procesor (BFPP):
Used when we want to override XML / annotations, because Spring reads XML / annotations to create the beans. If you want to provide a different configuration to Spring during creation (at run time), then you need to use BFPP. Creating the internal dependency graph is a one time process.
Bean Post Processor (BPP):
The above step happened only once. It's like creating the "menu" of beans. After creating the bean, if you want to change the bean properties, you can't make any changes to the XML / annotations. Instead, you can use the BPP for bean configuration change after creation. The BPP has 2 execution areas, one before #postconstruct and one after #postconstruct.
Real Time Example:
You want to place an online food order from Zomato. While ordering online, you give a list of food (XML/annotations) to the restaurant. But, just before the restaurant starts making the food, you call them and ask them to change the dish (BFPP). Now the food is ready to be delivered and you've received it (Bean is created). But you want to make some modifications (like salt or chilly powder), and you can do this before tasting the food (because you know restaurants never put enough salt), or even after tasting the food (this is before and after #postconstruct). Once the taste is good, then the food is ready (the bean is ready to use).
The BeanFactoryPostProcessor executes before bean Object instantiation (ie at the time Applicationcontext container is initialized)
BeanPostprocessor is executed after the bean object is created, as it can be executed before init() and after init().

How to access a bean definition from BeanPostProcessor

We register some beans with custom bean definition, in a BeanPostProcessor we need to access the bean definition
public Object postProcessBeforeInitialization(Object bean, String beanName)
I can make it ApplicationContextAware and then do:
((ConfigurableApplicationContext)applicationContext).getBeanFactory().getBeanDefinition(beanName)
but is it assured that the applicationContext is always ConfigurableApplicationContext?
Is there another way to access the bean definition from a BeanPostProcessor?
If you need to access BeanDefinition instances, you should use BeanFactoryPostProcessor instead of BeanPostProcessor.
BeanFactoryPostProcessor
Allows for custom modification of an application context's bean
definitions, adapting the bean property values of the context's
underlying bean factory. A BeanFactoryPostProcessor may interact with and modify bean definitions, but never bean instances.
BeanPostProcessor
Factory hook that allows for custom modification of new bean
instances, e.g. checking for marker interfaces or wrapping them with
proxies.

Spring: difference between Lookup method injection, Provider<T> , ObjectFactory and factoryBean

What are the differences between Lookup method injection, Provider<T>, ObjectFactory and factoryBean. If I want a new instance of a prototype (many times) into a singleton, which of them is the best solution?
And if I want a new instance (many times) of a prototype bean into a prototype?
please check my question too: How to instantiate spring managed beans at runtime?
As far as I understand the factoryBean is just a way to create bean with some complex instantiation logic. It is hard to define such logic in xml. It is well explained in spring documentation: http://springindepth.com/book/in-depth-ioc-factory-bean.html
Other three looks similar for me. But If you look at one spring issue https://jira.spring.io/browse/SPR-5192 you will find that javax.inject.Provider interface came from JSR-330 and I guess it was implemented in spring later than lookup method injection and looks like it is better solution. (The same thing is implemented in Google Guice DI)
Also with Object factory you have to write coupled with spring code(ObjectFactory requires spring import):
#Autowired
private ObjectFactory<PrototypeBean> beanFactory;
//...
beanFactory.getObject()
Upd
Lookup, beanFactory and Provider doesn't support passing any parameters, i.e. you have Provider#get() but there is no Provider#get(Object... args)

What is the difference between BeanPostProcessor and init/destroy method in Spring?

What is the difference between implementing the BeanPostProcessor interface and either using the init/destroy method attributes in the XML configuration file in Spring or implementing InitializingBean/DisposableBean interface?
This is pretty clearly explained in the Spring documentation about the Container Extension Points.
The BeanPostProcessor interface defines callback methods that you can
implement to provide your own (or override the container's default)
instantiation logic, dependency-resolution logic, and so forth. If you
want to implement some custom logic after the Spring container
finishes instantiating, configuring, and initializing a bean, you can
plug in one or more BeanPostProcessor implementations.
So in essence the method postProcessBeforeInitialization defined in the BeanPostProcessor gets called (as the name indicates) before the initialization of beans and likewise the postProcessAfterInitialization gets called after the initialization of the bean.
The difference to the #PostConstruct, InitializingBean and custom init method is that these are defined on the bean itself. Their ordering can be found in the Combining lifecycle mechanisms section of the spring documentation.
So basically the BeanPostProcessor can be used to do custom instantiation logic for several beans wheras the others are defined on a per bean basis.
Above answers clearly explains some of the very important aspect.
Apart from that it's also important to understand that both beanPostProcessor and init and destroy methods are part of the Spring bean life cycle.
BeanPostProcessor class has two methods.
1) postProcessBeforeInitialization - as name clearly says that it's used to make sure required actions are taken before initialization. e.g. you want to load certain property file/read data from the remote source/service.
2) postProcessAfterInitialization - any thing that you want to do after initialization before bean reference is given to application.
Sequence of the questioned methods in life cycle as follows :
1) BeanPostProcessor.postProcessBeforeInitialization()
2) init()
3) BeanPostProcessor.postProcessAfterInitialization()
4) destroy()
You may check this by writing simple example having sysout and check their sequence.
Init and Destroy callback methods are part of Spring bean life cycle phases. The init method is going to be executed after bean instantiation. Similarly, The destroy method is going to be executed before bean finalization.
We can implement this functionality using implementing interfaces InitializingBean and DisposableBean, or using annotations #postconstruct and #predestroy, or declare the <bean> with init-method and destroy-method attributes.
BeanPostProcessor interface is used for extending the functionality of framework if want to do any configuration Pre- and Post- bean initialization done by spring container.
For Example: By default, Spring will not aware of the #PostConstruct and #PreDestroy annotation. To enable it, we have to either register CommonAnnotationBeanPostProcessor or specify the <context:annotation-config /> in bean configuration file. Here CommonAnnotationBeanPostProcessor is predefined BeanPostProcessor implementation for the annotations. Like:
#Required enables RequiredAnnotationBeanPostProcessor processing tool
#Autowired enables AutowiredAnnotationBeanPostProcessor processing tool
And one more main diff is InitializingBean,DisposableBean related afterPropertiesSet() & destory() methods did not accept any paratmeters and return type also void, so we did not implement any custom logic.
But coming to BeanPostProcess methods postProcessBeforeInitialization(Object bean,String beanName) and postProcessAfterInitilization(Object bean,String beanName) are accept those two paramaters and return type also Object so we are able to write initilzation logics as well as any custom login based on the passing bean...
These both callback method feautes are including the bean life cycle and the following are the life cycle as follows
1) BeanPostProcessor.postProcessBeforeInitilazation()
2) #postConstruct or InitializingBean.afterPropertiesSet() or initialization method which is
defining in xml /* here also it's following the same oredr if three ways are availiable **/
3) BeanPostProcessor.postProcessAfterInitialization()
4) #preDestroy or DisposibleBean.destroy() or destroy method which is defining in xml
/* here also it's following the same oredr if three ways are availiable **/
Just a short supplement to all the answers above: If you have any generic logic, common logic that needs to be universally applied to all your Spring beans, such as the injection of a logger to your beans, setting of a properties file, setting default values to fields of your beans through reflection; you could put that logic into ONE single place: the #Overriden callbacks (eg: postProcessBeforeInitialization(Object arg0, String arg1) if you are implementing the BeanPostProcessor interface); instead of duplicating the same logic across all your beans.
a)The postProcessBeforeInitialization() will be called before initialization of the bean.
b)Once the bean gets initialized, the different callbacks methods are called in the following order as per the Spring docs:
Methods annotated with #PostConstruct
afterPropertiesSet() as defined by the InitializingBean callback interface
init method defined through the XML.
The main difference is that the above 3 methods get called after the initialization get completed by the postProcessBeforeInitialization() method.
Once these methods get completed the method postProcessAfterInitialization() will be called and then the destroy methods are called in the same order:
Methods annotated with #PreDestroy
destroy() as defined by the DisposableBean callback interface
destroy() method defined through the XML.

Resources