Spring Framework
- megha dureja
- Mar 7, 2021
- 4 min read

What is spring framework?
It is an open source container based framework used for building Java and J2EE applications (either web or standalone). The framework is widely used mainly in enterprise applications. It is built on top of two design concepts – Dependency Injection and Aspect Oriented Programming.
We have various modules for specific tasks under spring framework like
Spring Context – for dependency injection.
Spring AOP – for aspect oriented programming.
Spring DAO – for database operations using DAO pattern
Spring JDBC – for JDBC and DataSource support.
Spring ORM – for ORM tools support such as Hibernate
Spring Web Module – for creating web applications.
Spring MVC – for creating web applications, web services etc.
And ..
What is spring container?
It is a piece of code which reads spring bean configuration file and responsible for creating the objects, managing them, wiring them together, configuring them, as also managing their complete lifecycle. Eg. BeanFactory and ApplicationContext.
Why is spring container called IoC container?
It means now we have inverted the control of creating the object from our own using new operator to container or framework. Now it’s the responsibility of container to create object as required. We maintain one xml file where we configure our components, services, all the classes and their property. We just need to mention which service is needed by which component and container will create the object for us.
What is Spring configuration file?
Spring configuration file is called Spring Bean definition file.This file contains all configuration metadata/classes information which is needed for the container to know how to create a bean, register it, maintains its lifecycle and know about which beans/dependencies are needed.
You can declare your class and configured it to the framework by using XML or annotation or java based.
XML
<bean id="userService" class="com.sivalabs.myapp.service.UserService">
<property name="userDao" ref="userDao"/>
</bean>
<bean id="userDao" class="com.sivalabs.myapp.dao.JdbcUserDao">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="secret"/>
</bean>
Annotation
@Service
public class UserService
{
private UserDao userDao;
@Autowired
public UserService(UserDao dao){
this.userDao = dao;
}
...
...
}
@Repository
public class JdbcUserDao
{
private DataSource dataSource;
@Autowired
public JdbcUserDao(DataSource dataSource){
this.dataSource = dataSource;
}
...
...
}
Java
@Configuration
public class AppConfig
{
@Bean
public UserService userService(UserDao dao){
return new UserService(dao);
}
@Bean
public UserDao userDao(DataSource dataSource){
return new JdbcUserDao(dataSource);
}
@Bean
public DataSource dataSource(){
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("secret");
return dataSource;
}
}
Design Patterns being used in Spring framework?
List of Core/Common GoF / J2EE Design Patterns which are internally used by Spring / based upon:
1. MVC - The advantage with Spring MVC is that your controllers are POJOs as opposed to being servlets. This makes for easier testing of controllers.
2. Front controller - Spring provides "DispatcherServlet" to ensure an incoming request gets dispatched to your controllers.
3. View Helper - Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from presentation in views.
4. Singleton - Beans defined in spring config files are singletons by default.
5. Prototype - Instance type can be prototype.
6. Factory - Used for loading beans through BeanFactory and ApplicationContext.
7. Builder - Spring provides programmatic means of constructing BeanDefinitions using the builder pattern through Class "BeanDefinitionBuilder".
8. Template - Used extensively to deal with boilerplate repeated code (such as closing connections cleanly, etc..). For example JdbcTemplate.
9. Proxy - Used in AOP & Remoting.
10. DI/IOC - It is central to the whole BeanFactory/ApplicationContext stuff.
11. Observer
How to auto-wire two different beans of same class?
A class which wraps a connection pool, the class gets its connection details from a spring configuration as shown below:
<bean id="jedisConnector" class="com.legolas.jedis.JedisConnector" init-method="init" destroy-method="destroy">
<property name="host" value="${jedis.host}" />
<property name="port" value="${jedis.port}" />
</bean>
<bean id="jedisConnectorPOD" class="com.legolas.jedis.JedisConnector" init-method="init" destroy-method="destroy">
<property name="host" value="${jedis.pod.host}" />
<property name="port" value="${jedis.pod.port}" />
</bean>
=> @Resource
@Resource(name="jedisConnector")
JedisConnector beanA;
@Resource(name="jedisConnectorPOD")
JedisConnector beanB;
@Resource
JedisConnector jedisConnector;
@Resource
JedisConnector jedisConnectorPOD;
=> @Autowired with @Qualifier
@Autowired
@Qualifier("jedisConnector")
JedisConnector beanA;
@Autowired
@Qualifier("jedisConnectorPOD")
JedisConnector beanB;
=> If bean scope is singleton by default then how it's creating two different objects of same class?
Singleton has a slightly different meaning in spring - it's not about guaranteeing 1 instance per class. It just means every time you call "context.getBean("jedisConnector")" you'll get the same object, as opposed to "prototype" which means getting a different instance each time to call context.getBean("jedisConnector")
try this
Object x1=context.getBean("jedisConnector");
Object x2=context.getBean("jedisConnector");
If "jedisConnector" is singleton you'll get the same reference. If prototype you'll get two separate instances.
Spring Bean Scopes:-
Singleton - only one instance of bean per spring container.
This bean scope is default and it enforces the container to have only one instance per spring container irrespective of how much time you request for its instance. This singleton behavior is maintained by bean factory itself.
Prototype - a new instance every time bean is requested.
This bean scope just reverses the behavior of singleton scope and produces a new instance each and every time a bean is requested.
Request - single bean instance per http request.
a new bean instance will be created for each web request made by client. As soon as request completes, bean will be out of scope and garbage collected.
Session - single bean instance per http session.
This ensures one instance of bean per user session. As soon as user ends its session, bean is out of scope.
Global-session - single bean instance per global http session.
It is a little different in sense that it is used when application is portlet based. In portlets, there will be many applications inside a big application and a bean with scope of ‘global-session’ will have only one instance for a global user sessionthat is shared among all of the various portlets that make up a single portlet web application.
Application - a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
- An object of ServletContext is created by the web container at time of deploying the project.
- There is only one ServletContext object per web application.
Websocket - a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
Request, Session and Global Session scopes are valid in the context of a web-aware Spring ApplicationContext(WebApplicationContext). This means that you can only use these scoped beans in a an application deployed to a web server. Spring can be used in applications that run in standard JVMs along with applications that run in servlet containers (Tomcat, etc). Request, Session and Global session however, only exists in web servers so it has no meaning if the application is running in a standard desktop environment.
If you use these scopes with regular Spring IoC containers such as the ClassPathXmlApplicationContext, you get an IllegalStateException complaining about an unknown bean scope.
Comments