Saturday, January 2, 2016

Spring Framework

Spring Framework:- Spring 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.


Spring Container 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.
The org.springframework.beans and org.springframework.context packages provide the basis for the Spring Framework’s IoC container.

Inversion of control 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.


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;
    }
} 
 
Spring Without Annotations
-> create maven project
-> add dependencies
-> create source folder -> src/main/resources
-> create applicationContext.xml/spring configuration file -> beans definition
<beans spring-beans,spring-context>
<bean id>
</bean>
</beans>
-> create bean/class
-> enter bean id, class, property name in applicationContext.xml file
-> main class ->
1) load applicationContext
2) initiate bean by calling getBean() method, not by new operator
3) do stuff


Spring With Annotations
-> create maven project
-> add dependencies
-> create source folder -> src/main/resources
-> create applicationContext.xml/spring configuration file -> beans definition
<beans spring-beans,spring-context>
<bean id>
</bean>
</beans>
-> create bean/class and put required @annotations over the bean
-> enter <context:annotation-config/> and <context:component-scan base-package="*path of base package*"/> applicationContext.xml file
-> main class ->
1) load applicationContext
2) initiate bean by calling getBean() method, not by new operator
3) do stuff


Reflection
Class is the start point of using Java reflection API. We can use Class.forName("classname") to get a Class descriptor and then initialize an object, invoke methods, etc. Reflection is used in spring framework.


Spring uses bean configuration such as:
<bean id="someID" class="com.example.Foo">
<property name="someField" value="someValue" />
</bean>
When the Spring context processes this <bean> element, it will use Class.forName(String) with the argument "com.example.Foo" to instantiate that Class.

It will then again use reflection to get the appropriate setter for the <property> element and set its value to the specified value.

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 -

Autowiring two different beans of same class / Multiple beans referring to the 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?

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 Life cycle
ApplicationContext/BeanFactory is responsible for managing life cycle of beans.

CallBack Interfaces

Aware Interfaces

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, 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.

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 session that 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.


Difference between session / request?
scope="session"
means through out the application ( till the session gets expired). Your can keep the values in session no matter how many JPSs you are visiting of that application. It remains there in session until you close your browser.

scope="request"
means for that particular action only you are keeping the values. In this if you call another action or redirects to another JSP , it gets removed.


Difference between application / request?
Application scope is for whole application and request is for just a request by the client.

Web Development

Design Phase:- Below all these represent different stages of the UX/UI design flow:- Wireframes represent a very basic & visual repr...