Spring InitializingBean interface - spring

In XML file in spring we have two bean with different id but same class. They have the same properties offcourse. Now I have InitializingBean interface and in afterPropertySet() I am just printing the value of properties.
Its printing the values two times for me?

According Spring Documentation:
afterPropertySet()
Invoked by a BeanFactory after it has set all bean properties supplied (and satisfied BeanFactoryAware and ApplicationContextAware).
So the short answer on your question is: yes
Spring doesn't manipulate classes or object. Spring manipulates Bean Entity. It is the simplest object manipulated by Spring IOC. Bean has additional behaivior rules introduced by Spring.
If you create two beans for example with Singleton scope and not Lazy initializated Spring creates two instances of your class.

Probably you are calling this Class also invoking a Test or by launching a Integration test like this . check the breakpoints , if you are using SpringRunner, try to mock the component

Related

Standard Scope for Spring classes

In a spring MVC app , by default all beans are singleton ,but what should be the standard scopes for below classes according to good programming practices:
1.DAO classes
2.Controller classes
3.DTO classes
4.Service classes
I have read that DAO and Controller classes should be singleton scoped and DTO classes should not be beans so not annotated, whenever required, DTO classes should be instantiated using "new".
What will be the scope of #Service classes ?
And Which classes will have the Request and Session scopes if none of the above classes are created in these 2 scopes?
First of all not classes, but Spring managed beans have a scope. Difference is that you can have classes in your application that you didn't configure to be managed by Spring (So for example you didn't provide #Component annotation)
For the Spring managed beans default scope is Singleton. That means Spring container will provide the same instance everytime you ask for that bean to be autowired.
You can change that default scope with for example #Scopeannotation. So to answer your question, all of the above mentioned choices would have default scope of singleton but you could changed that to be requestor sessionscope if you would like (only applicable in web applications though). You can read more about setting scopes here.
ps. DTO classes are usually not declared to be managed by Spring - letting Spring manage a simple data transfer object doesn't make much sense.
So basically two things to consider here. The 1st is that if a bean is required to be declared as a spring bean . It depends on if you need to use the spring features for this class such as #Transactional , #Async , #PreAuthorize , #Autowired (i.e dependency injection) , or ensure the bean has certain scope etc. If not , it is simpler not define it as a spring bean and simply create it by yourself.
So the following types of the classes are required to define them as spring bean in most cases:
DAO because most probably need to inject EntityManager or JdbcTemplate to it
Controller because it is a part of spring-mvc and you need to define it as a bean such that you can use #RequestMapping / #GetMapping / #PostMapping / #PutMapping / #DeletMapping / #PatchMapping etc. on its method.
Service class because you need to inject it into the controller and you need to use #Transactional to manage the DB transaction for its method.
For DTO , in most case you can create it by yourself since it is just a data container in nature and does not require to use any spring features.
The 2nd thing to consider is what scope does a bean should be. You mainly need to think about if an instance of that class is okay to be executed safely by multiple request (i.e thread) concurrently. If yes , you can simply use the default singleton scope. If not , you can think about if you want each HTTP request (i.e #RequestScope) or each HTTP session (i.e. #SessionScope) has their own instance of that class to work with. For example , if you are implementing some shopping cart , you most probably want that the HTTP session has their won instance of a shopping cart and so you should use #SessionScope for the shopping cart.

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.

Inject properties into object which is not a spring managed bean

I have a spring application where in some cases I need to create an object at runtime, as opposed to a spring injected bean. This object should be created with properties that come from the application context however. If this object is not spring-injected, how can I still take advantage of IoC? Should I make these object properties static and inject them into a bean via non-static setters?
You can still inject properties for object which is not created by spring.
To do that you should use #Configurable annotation. And you should enable LoadTimeWeaving or CompileTimeWeaving. But I think that can be overkill for your situation.

Getting Spring object instantiation right

I'm new to Spring and a little confused about how it works. I get that I can use the application context to instantiate beans and have them populated. However, is the idea that I should be able to just write Bean b = new Bean() and then have Spring to somehow automagically populate that Bean?
I'm experimenting with Spring in a web application, and as far as I can see I need to inject the ApplicationContext into, say, the servlets to be able to instantiate other beans (services, daos etc.) from there. It's a bit cumbersome, but probably works.
However, is Spring meant to be able to hook into any object instantiation which happens on classes defined as beans in applicationContext.xml?
Spring is an Inversion of Control container. A bean is an object whose life cycle is managed by Spring. If you want Spring to populate an object, it needs to go through Spring, ie. it needs to be bean.
is Spring meant to be able to hook into any object instantiation
which happens on classes defined as beans in applicationContext.xml?
Spring doesn't hook into anything. You configure your beans and the relationships between them with Spring and Spring handles creating the instances and linking them up.
For domain objects, Spring provides a solution via the #Configurable annotation: http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#aop-atconfigurable
It requires compile- or load-time-weaving and, thus, introduces some additional complexity but having the convenience of using the standard new Bean() syntax plus Spring's autowiring is worth it in my opinion.
Alternatively, you could define your domain objects as beans with prototype scope and use some factory to create them using the Spring ApplicationContext.getBean() method. With a scope of prototype a new instance will be returned every time and since you go through the ApplicationContext, Spring will do all the dependency injection magic as usual.
As for services and other beans with singleton scope, you would typically NOT retrieve them by first injecting the ApplicationContext and using it but instead you would inject them via either a constructor, setter or annotation-based strategy. The documentation covers that in detail: http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#beans-factory-collaborators

Spring calling 'destroy' method on session/request scoped beans

How does Spring know when to call 'destory' method on a session/request scoped bean (in other words, how does it detect that the concerned bean is going out of scope)?
I read somewhere that it uses request/session listeners to be notified of these events. But these listners need to be defined in web.xml, and there's no mention of defining such listeners in Spring literature. So how does this work?
The org.springframework.web.servlet.DispatcherServlet does it. It uses own code, e.g. the org.springframework.web.context.request.RequestAttributes#registerDestructionCallback callback list functionality to register all these scoped beans.
and there's no mention of defining such listeners in Spring literature
Oh, there is:
To support the scoping of beans at the request, session, and global session levels (web-scoped beans), some minor initial configuration is required before you define your beans.[...]
If you use a Servlet 2.4+ web container, [...] you need to add the following javax.servlet.ServletRequestListener to the declarations in your web applications web.xml file[...]
From: 4.5.4.1 Initial web configuration.
Also note that Spring does not call destroy on prototype-scoped beans.
You can implement the interface DisposableBean and InitializingBean for session scoped bean.
The org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work after all necessary properties on the bean have been set by the container. The InitializingBean interface specifies a single method afterPropertiesSet().
Implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container containing it is destroyed. The DisposableBean interface specifies a single method destroy().
Read more about it here: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-nature

Resources