Spring MVC controller initialization code - spring

I have a spring MVC project, in one of the controllers, i have a DB connection object that needs to be initialized only once in the controller, what is the best approach to follow when adding this initialization code, for now, i used a static block in the controller where i added the initialization code, do u have any other suggestions.
thanks in advance

Make it a Spring bean. That way it's a singleton (by default), and can be injected wherever you want.
Note that even if you leave its initialization in the controller, making it static is useless, since a controller is also a Spring bean, which is a singleton by default.

Well in spring you don't need to initialize the db connections yourself , It provide support for db connections
You just need to specify the the bean in .xml files and directly autowired that bean into your controller
use dao pattern to implement database connections see some example it will be easy container will manage db connections object life cycle for you
Thanks,
Himanshu

May I recommend you read the Spring reference guide for Object Relational Mapping and Data Access? Its quite comprehensive and details how to set up a data source, session factory, implement DAO classes, transaction management etc... Hopefully you will find this is a good place to start.

Related

why #RestController by default use singleton scope?

I am actually a EJB developer and very new in spring framework.
i find a couples of conflict conceptually. Like ..
#RestController use by default scope which is singleton. By single object per loc have to manage heavy trafic.
is it a good design?
Of course, it is a good design because the same instance of the object will be reused instead of keep creating it each time you need it. That is the whole point of that design pattern.
Here is a great example where singleton comes to the rescue.
https://rules.sonarsource.com/java/RSPEC-2119
By default, spring will take care of the creation and destruction of all singleton beans, while the prototype has to be manually handled. Therefore in a lot of cases prototype scope is for custom beans made by developers.
In SpringMVC Controller layer, #Scope("prototype") vs #Scope("singleton")
is it a good design?
Yes, all beans in Spring are singletons (by default).
We have 100+ controllers in several applications and it works perfectly.
If you really need to instantiate controllers more than once, you can, of course, consider other bean scopes (see brief explanation of scopes here https://www.baeldung.com/spring-bean-scopes)

Selecting the right candidates for spring bean. What to what not to

Last year when I started learning spring I remember an article that expalined that not all pojos are to be defined as beans. So I'm planning to create a web app say EmployeeMaintenance. CRUD Functionalities are there. I will surely end up creating pojos like Employee , EmployeeSupplementaryDetails, Address etc. Should I makes these beans and configure them in xml or annotate whatever. I'm sure my understanding of bean is not enough. I know that Dbconn , services etc should definitely be declared as bean.
All I need is what are the parameters I should consider before I make a pojo a Spring Bean.
General rule for making Java class a Spring bean is to ask yourself if you need to inject object into some other object or if you want the object to be managed by Spring components. The classes you listed as example doesn't seem to be good candidates for being Spring beans - they represent model data and will be passed as some service's methods parameters.
Examples of typical CRUD application beans:
EmployeeService (you would want to inject it to controller or other service)
EmployeeRepository / EmployeeDao
EmployeeController (it will be bean managed by Spring's MVC framework)
etc.
Spring beans are building blocks of your application. Let's suppose you need to create web application for storing and managing employees records (creating, retrieving, updating, deleting). What you will need is web controller that will handle incoming requests for several operations (EmployeeController). Good practice is that controller doesn't implement any business logic - all it should do is to delegate work to service beans. So you would need bean like EmployeeService. Then controller would ask service to do some work (give me employees list / remove John Smith from database / change salary for Ann Jackson / etc). So service will be controller's dependency (service is injected into controller). Service can also have some dependencies (like repository object, which is responsible for handling communication with data storage) and these dependencies would be injected to service. Dependency management is Spring's core feature.
Good practice in object oriented programming is to have small classes that are responsible for doing one kind of actions. Such objects are much easier to test and understand. The more classes you have, the building application from blocks is harder, so it's worth to delegate it to framework like Spring. Without Spring you would need to create controller class, then inside of it create service, then inside of it create other dependencies and so on. Spring does it for you, so all you need to do is to declare dependencies and they will be injected automatically. If you want to replace implementation of your service with another (for example repository that used XML file for storing data with repository storing data in relational database) then you just have to change your bean definition.
Regarding to beans managed by Spring, typical example is database transaction manager (eg. org.springframework.orm.jpa.JpaTransactionManager). If you define such bean, and declare which methods should be transactional, then Spring will take care of transactions management (will open, commit or rollback transactions automatically).

In-memory structure in Spring

I'm a Spring novice user.
I have a database table which is static in nature and contains only a few records.I want a Map-like structure(id - name) that holds two columns of this table. This Map must be loaded/initialized when the web application is started and must be applicable throughout the application's context, independent of the users sessions and must be read-only. This way, I can save a lot of DB queries as the different operations will simply read from this Map.
While I'm aware of ServletContextListener etc. of Java EE, I don't know how to achieve the same in Spring. Is a Spring Service bean the right place/way to initialize and store such a Map?
Please guide me about the same.
You can create a regular spring bean exposing a method which loads the data you require from the database and stores it in your map. Annotate this method with #PostConstruct and spring will ensure that it is called when your application context starts, hence loading your map.
You could use springs JdbcTemplate to load your data within this method
See Spring PostConstruct doco for information on the #PostConstruct annotation
See JdbcTemplate doco for information on JdbcTemplate
You can configure lists, sets and maps in a Spring XML configuration. See here for more examples.

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.

How do I pass parameters between request-scoped beans

This is a question that has been bothering me for sometime. My application uses ICEFaces for our UI framework and Spring 2.5 for Dependency Injection. In addition, Spring actually maintains all of our backing beans, not the ICEFaces framework, so our faces-config is basically empty.
Navigation is not even really handled through navigation-rules. We perform manual redirects to new windows using window.open.
All of our beans are defined in our appContext file as being request-scoped. I have Page ABC which is backed by BackingBeanABC. Inside that backing bean, I have a parameter say:
private Order order;
I then have Page XYZ backed by BackingBeanXYZ. When I redirect from page ABC to page XYZ, I want to transfer the 'order' property from ABC to XYZ. The problem is since everything is request-scoped and I'm performing a redirect, I am losing the value of 'description'.
There has got to be an easier way to pass objects between beans in request scope during a redirect. Can anyone assist with this issue?
Session scope solves your issue.
You can read more about it in Spring's reference documentation.
Another alternative is to set the order object directly on the HttpSession object. I would have prefered that and only have your services, controllers and repositories managed by Spring.
Create a single session scoped bean that the request scoped beans can reference via the FacesContext.

Resources