Why we need Spring ? when to Use of it ?
-----------------------------------------------------------
- Spring helps you extricate the logic of configuration from your business logic. It encourages the clean separation of concerns you need to be able to unit test code, inegrate it in one environment and then deploy it in any of numerous others, all without changing anything besides the configuration. Spring works in a public static void main(){} application, a lean web server like Tomcat, Jetty, or tomcat Server, on a Java EE application server or in environments like the cloud, all with just changes to the configuration, which Spring makes easy. Nothing else has this level of portability for even basic applications.
- Spring provides the powerful trinity of AOP, portable service abstractions and dependency injection, which everything else builds on. The rest of the Spring framework, Spring MVC, Spring Integration, Spring Batch, etc., all embrace these concepts to provide higher level solutions for specific types of problems in a consistent way, leveraging the same consistent concepts throughout. So, there's no magic, and any user is free to take advantage of these features from the lowest level support all the way to the specialized, abstract frameworks. This is a good example of the idea of "one kind of stuff" - everything in Spring is just a POJO. You don't have to care if it's any of the numerous EJB types in one place, a servlet in another, a JCA connector in another, a JSF managed bean, a Struts action, etc. To Spring, it's all just POJOs that get adapted to those types of components. You can take advantage of services in the same way anywhere.
- Spring's the only platform built from the ground up with choice as a key feature. The mission statement, if you will, is portability and innovation in service of productivity. With Spring, you'll find clean integrations with numerous web frameworks, persistence frameworks (and indeed, numerous data base types beyond just RDBMSes!), integration and messaging middle-ware, cloud environments, etc.
- Spring tackles the tough problems. Java EE, for example, has featured an ever changing and increasingly backwards compatible solution for transactional data services that makes assumptions about the nature of the services that you can't change. It's also featured a low level API for messaging (JMS), a low level API for RDBMS-based data-access (JDBC), and a very arcane model for third-party connectors to plugin to an otherwise top-heavy application server called JCA, Servlets, JSPs and JSF for web applications, JAXRPC, JAXRS, JAXWS, etc., for old-style SOAP services, restful services, and document-oriented, contract-first SOAP services, etc. If you'r application fits in that mold, then great. Even there, Spring's got powerful solutions to help damatially simplify things (a consistent transaction API, no matter what the resource, the JdbcTemplate, the JmsTemplate, etc), but if you've got other problems to solve, then you're out of luck. Want to use Flex? Want to handle batch processes? Job scheduling? Caching? Systems integration? Use any of the dozens of other very powerful and very popular web frameworks, etc? Spring has options to help.
- Spring's an a la carte model. Be as heavy or as light as you like - the core framework works perfectly in a public static void main application with just two jars. You can add as you like.
- It's backwards compatible. The idea of a "standard" used to mean that users were insulated from volatile APIs and unportable features. However, to wit, huge chunks of EJB as introduced in Java EE 5, J2EE 1.4 and 1.3 have been deprecated, JAXRPC's deprecated, JSF 2 looks little like JSF 1, etc. Basically, if you bet on J2EE 8 years ago, you most certainly would have had to rewrite several parts of your app to track the latest updates.
By comparison, a Spring bean as defined in Spring 1.0 would still work today if the doctype DTD declarations were replaced with the XSDs, *and* you'd have more options in the APIs, and for deployment scenarios, not less: Spring will work on those same J2EE 1.4 applications servers that Java EE 5 code won't ;-) To make things worse, the current crop of application servers are implementing 'profiles,' which not only don't require continued implementation of APIs previously supported, they remove entire chunks of the platform, effectively boxing you into an older version unless you switch to a different server (usually costy) that does continue to support the older technology.
- It's here, now. NoSQL/Big Data / the cloud are here now. So is Spring Data and Spring Hadoop, for example. Android is here, now. So is Spring Android. Java EE is by definition always behind the current trends. Parts of JavaEE 6 were started in 2005/6, and it's already been available for a year and a half. So the design of Java EE 6 is in some cases 5+ years old. Want cloud and big data support? Well, Java EE 7 is *supposed* to have some of it in late 2012... No mention of mobile support, however. Meanwhile, not all vendors (in fact, most have not) have shipped Java EE 6 implementations yet!
Example :
============
Note:- you can't re-use of Inner bean.
Q . Are Spring Beans Thread Safe?
Answer : No.
Spring has different bean scopes (e.g. Prototype, Singleton, etc.) but all these scopes enforce is when the bean is created. For example a "prototype" scoped bean will be created each time this bean is "injected", whereas a "singleton" scoped bean will be created once and shared within the application context. There are other scopes but they just define a time span (e.g. a "scope") of when a new instance will be created.
The above has little, if anything to do with being thread safe, since if several threads have access to a bean (no matter the scope), it would only depend on the design of that bean to be or not to be "thread safe".
The reason I said "little, if anything" is because it might depend on the problem you are trying to solve. For example if you are concerned whether 2 or more HTTP requests may create a problem for the same bean, there is a "request" scope that will create a new instance of a bean for each HTTP request, hence you can "think" of a particular bean as being "safe" in the context of multiple HTTP requests. But it is still not truly thread safe by Spring since if several threads use this bean within the same HTTP request, it goes back to a bean design (your design of a bean backing class).
Q . How to Make/Design a Thread Safe "Object"?
Answer : There are several ways, probably too long to list here but here are a few examples:
Design your beans immutable: for example have no setters and only use constructor arguments to create a bean. There are other ways, such as Builder pattern, etc..
Design your beans stateless: for example a bean that does something can be just a function (or several). This bean in most cases can and should be stateless, which means it does not have any state, it only does things with function arguments you provide each time (on each invocation)
Design your beans persistent: which is a special case of "immutable", but has some very nice properties. Usually is used in functional programming, where Spring (at least yet) not as useful as in imperative world, but I have used them with Scala/Spring projects.
Design your beans with locks [last resort]: I would recommend against this unless you are working on a lower level library. The reason is we (humans) are not good thinking in terms of locks. Just the way we are raised and nurtured. Everything happens in parallel without us needing to "put that rain on pause, let me get an umbrella". Computers however are all about locks when you are talking "multiple things at the same time", hence there are some of us (exceptional people) who are doing their fair share and implementing libraries based on these locks. Most of other humans can just use these libraries and worry not about concurrency.
What is the difference between Bean Factory and Application Context?
On the surface, an application context is same as a bean factory. But application context offers much more.
► Application contexts provide a means for resolving text messages, including support for i18n of those messages.
► Application contexts provide a generic way to load file resources, such as images.
► Application contexts can publish events to beans that are registered as listeners.
► Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.
► ResourceLoader support: Spring�s Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances.
► MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.
What is the typical Bean life cycle in Spring Bean Factory Container?
The spring container finds the beans definition from the XML file and instantiates the bean.
► Using the dependency injection, spring populates all of the properties as specified in the bean definition
► If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean's ID.
► If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
► If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.
► If an init-method is specified for the bean, it will be called.
► Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
What do you mean by Auto Wiring?
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes.
no
► byName
► byType
► constructor
► autodetect.
What is XMLBeanFactory?
BeanFactory has many implementations in Spring. But one of the most useful one is org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. To create an XmlBeanFactory, pass a java.io.InputStream to the constructor. The InputStream will provide the XML to the factory. For example, the following code snippet uses a java.io.FileInputStream to provide a bean definition XML file to XmlBeanFactory.
Explain Bean lifecycle in Spring framework?
1. The spring container finds the beans definition from the XML file and instantiates the bean.
2. Using the dependency injection, spring populates all of the properties as specified in the bean definition.
3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the beans ID.
4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
5. If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.
6. If an init-method is specified for the bean, it will be called.
7. Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
How to integrate your Struts application with Spring?
To integrate your Struts application with Spring, we have two options:
► Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their dependencies in a Spring context file.
► Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a getWebApplicationContext() method.
What is IOC or inversion of control?
As the name implies 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. This concept is known as dependency injection because all object dependency (resources) is injected into it by framework.
Example:
<bean id="createNewStock" class="springexample.stockMarket.CreateNewStockAccont">
<property name="newBid"/>
</bean>
In this example CreateNewStockAccont class contain getter and setter for newBid and container will instantiate newBid and set the value automatically when it is used. This whole process is also called wiring in Spring and by using annotation it can be done automatically by Spring, refereed as auto-wiring of bean in Spring.
-----------------------------------------------------------
- Spring helps you extricate the logic of configuration from your business logic. It encourages the clean separation of concerns you need to be able to unit test code, inegrate it in one environment and then deploy it in any of numerous others, all without changing anything besides the configuration. Spring works in a public static void main(){} application, a lean web server like Tomcat, Jetty, or tomcat Server, on a Java EE application server or in environments like the cloud, all with just changes to the configuration, which Spring makes easy. Nothing else has this level of portability for even basic applications.
- Spring provides the powerful trinity of AOP, portable service abstractions and dependency injection, which everything else builds on. The rest of the Spring framework, Spring MVC, Spring Integration, Spring Batch, etc., all embrace these concepts to provide higher level solutions for specific types of problems in a consistent way, leveraging the same consistent concepts throughout. So, there's no magic, and any user is free to take advantage of these features from the lowest level support all the way to the specialized, abstract frameworks. This is a good example of the idea of "one kind of stuff" - everything in Spring is just a POJO. You don't have to care if it's any of the numerous EJB types in one place, a servlet in another, a JCA connector in another, a JSF managed bean, a Struts action, etc. To Spring, it's all just POJOs that get adapted to those types of components. You can take advantage of services in the same way anywhere.
- Spring's the only platform built from the ground up with choice as a key feature. The mission statement, if you will, is portability and innovation in service of productivity. With Spring, you'll find clean integrations with numerous web frameworks, persistence frameworks (and indeed, numerous data base types beyond just RDBMSes!), integration and messaging middle-ware, cloud environments, etc.
- Spring tackles the tough problems. Java EE, for example, has featured an ever changing and increasingly backwards compatible solution for transactional data services that makes assumptions about the nature of the services that you can't change. It's also featured a low level API for messaging (JMS), a low level API for RDBMS-based data-access (JDBC), and a very arcane model for third-party connectors to plugin to an otherwise top-heavy application server called JCA, Servlets, JSPs and JSF for web applications, JAXRPC, JAXRS, JAXWS, etc., for old-style SOAP services, restful services, and document-oriented, contract-first SOAP services, etc. If you'r application fits in that mold, then great. Even there, Spring's got powerful solutions to help damatially simplify things (a consistent transaction API, no matter what the resource, the JdbcTemplate, the JmsTemplate, etc), but if you've got other problems to solve, then you're out of luck. Want to use Flex? Want to handle batch processes? Job scheduling? Caching? Systems integration? Use any of the dozens of other very powerful and very popular web frameworks, etc? Spring has options to help.
- Spring's an a la carte model. Be as heavy or as light as you like - the core framework works perfectly in a public static void main application with just two jars. You can add as you like.
- It's backwards compatible. The idea of a "standard" used to mean that users were insulated from volatile APIs and unportable features. However, to wit, huge chunks of EJB as introduced in Java EE 5, J2EE 1.4 and 1.3 have been deprecated, JAXRPC's deprecated, JSF 2 looks little like JSF 1, etc. Basically, if you bet on J2EE 8 years ago, you most certainly would have had to rewrite several parts of your app to track the latest updates.
By comparison, a Spring bean as defined in Spring 1.0 would still work today if the doctype DTD declarations were replaced with the XSDs, *and* you'd have more options in the APIs, and for deployment scenarios, not less: Spring will work on those same J2EE 1.4 applications servers that Java EE 5 code won't ;-) To make things worse, the current crop of application servers are implementing 'profiles,' which not only don't require continued implementation of APIs previously supported, they remove entire chunks of the platform, effectively boxing you into an older version unless you switch to a different server (usually costy) that does continue to support the older technology.
- It's here, now. NoSQL/Big Data / the cloud are here now. So is Spring Data and Spring Hadoop, for example. Android is here, now. So is Spring Android. Java EE is by definition always behind the current trends. Parts of JavaEE 6 were started in 2005/6, and it's already been available for a year and a half. So the design of Java EE 6 is in some cases 5+ years old. Want cloud and big data support? Well, Java EE 7 is *supposed* to have some of it in late 2012... No mention of mobile support, however. Meanwhile, not all vendors (in fact, most have not) have shipped Java EE 6 implementations yet!
Example :
============
Spring
IOC (Inversion of Control):-
Ioc can be implement in 2 ways.
1) Dependency Lookup.
2) Dependency injection.
1) Dependency Lookup:- if you want any objects to use, you can create that objects, or you can lookup and get from registry. This is a normal flow of control.
2) Dependency injection:- dependency injection facility inject the require object automatically.
you can implement dependency injection in 2 ways.
1) setter injection.
2) constructor injection.
Note:- Detailed theory i will provide latter.
Example of IOC:-
File require
1) A.java
2) B.java
3) Hello.java
4) Test.java
5) chirag.xml
Jar File require
1) spring-core 3.0.5.jar
2) spring-asm 3.0.5.jar
3) commons-logging-1.1.1.jar
4) spring-context-3.0.5.jar
5) spring-aop-3.0.5.jar
6) spring-beans-3.0.5.jar
7) spring-expression-3.0.5.jar
8) aopalliance-1.0.jar
1) A.java
public class A {
int a;
String str;
public A()
{
}
public A(int a,String str)
{
this.a = a;
this.str = str;
}
public void showA()
{
System.out.println("A Class value a = "+a);
System.out.println("A Class value str = "+str);
}
}
2) B.java
package com.test.Spring;
public class B {
int b;
String str;
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public void showB()
{
System.out.println("B Class value a = "+b);
System.out.println("B Class value str = "+str);
}
}
3) Hello.java
package com.test.Spring;
public class Hello {
A aobj;
B bobj;
Hello(B bobj)
{
this.bobj = bobj;
}
public A getAobj() {
return aobj;
}
public void setAobj(A aobj) {
this.aobj = aobj;
}
public void showHello()
{
aobj.showA();
bobj.showB();
}
}
4) Test.java
package com.test.Spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String as[])
{
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("chirag1.xml");
Hello hello =(Hello)applicationContext.getBean("hello");
hello.showHello();
}
}
5) applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="aobj" class="com.test.Spring.A">
<constructor-arg>
<value>1111</value>
</constructor-arg>
<constructor-arg value="Chirag Java" />
</bean>
<bean id="bobj" class="com.chirag.Spring.B">
<property name="b">
<value>2222</value>
</property>
<property name="str" value="Chirag Java Master" />
</bean>
<bean id="hello" class="com.chirag.Spring.Hello">
<constructor-arg>
<ref local="bobj" />
</constructor-arg>
<property name="aobj">
<ref local="AAobj" />
</property>
</bean>
</beans>
Inner Bean you can define as follow:-
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="bobj" class="com.test.Spring.B">
<property name="b">
<value>2222</value>
</property>
<property name="str" value="Chirag Java Master" />
</bean>
<bean id="hello" class="com.chirag.Spring.Hello">
<constructor-arg>
<ref local="bobj" />
</constructor-arg>
<property name="aobj">
<bean id="AAAobj" class="com.chirag.Spring.A"> <!-- Inner bean define here !-->
<constructor-arg>
<value>77712</value>
</constructor-arg>
<constructor-arg value="Hi Ok"/>
</bean>
</property>
</bean>
</beans>
Ioc can be implement in 2 ways.
1) Dependency Lookup.
2) Dependency injection.
1) Dependency Lookup:- if you want any objects to use, you can create that objects, or you can lookup and get from registry. This is a normal flow of control.
2) Dependency injection:- dependency injection facility inject the require object automatically.
you can implement dependency injection in 2 ways.
1) setter injection.
2) constructor injection.
Note:- Detailed theory i will provide latter.
Example of IOC:-
File require
1) A.java
2) B.java
3) Hello.java
4) Test.java
5) chirag.xml
Jar File require
1) spring-core 3.0.5.jar
2) spring-asm 3.0.5.jar
3) commons-logging-1.1.1.jar
4) spring-context-3.0.5.jar
5) spring-aop-3.0.5.jar
6) spring-beans-3.0.5.jar
7) spring-expression-3.0.5.jar
8) aopalliance-1.0.jar
1) A.java
public class A {
int a;
String str;
public A()
{
}
public A(int a,String str)
{
this.a = a;
this.str = str;
}
public void showA()
{
System.out.println("A Class value a = "+a);
System.out.println("A Class value str = "+str);
}
}
2) B.java
package com.test.Spring;
public class B {
int b;
String str;
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public void showB()
{
System.out.println("B Class value a = "+b);
System.out.println("B Class value str = "+str);
}
}
3) Hello.java
package com.test.Spring;
public class Hello {
A aobj;
B bobj;
Hello(B bobj)
{
this.bobj = bobj;
}
public A getAobj() {
return aobj;
}
public void setAobj(A aobj) {
this.aobj = aobj;
}
public void showHello()
{
aobj.showA();
bobj.showB();
}
}
4) Test.java
package com.test.Spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String as[])
{
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("chirag1.xml");
Hello hello =(Hello)applicationContext.getBean("hello");
hello.showHello();
}
}
5) applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="aobj" class="com.test.Spring.A">
<constructor-arg>
<value>1111</value>
</constructor-arg>
<constructor-arg value="Chirag Java" />
</bean>
<bean id="bobj" class="com.chirag.Spring.B">
<property name="b">
<value>2222</value>
</property>
<property name="str" value="Chirag Java Master" />
</bean>
<bean id="hello" class="com.chirag.Spring.Hello">
<constructor-arg>
<ref local="bobj" />
</constructor-arg>
<property name="aobj">
<ref local="AAobj" />
</property>
</bean>
</beans>
Inner Bean you can define as follow:-
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="bobj" class="com.test.Spring.B">
<property name="b">
<value>2222</value>
</property>
<property name="str" value="Chirag Java Master" />
</bean>
<bean id="hello" class="com.chirag.Spring.Hello">
<constructor-arg>
<ref local="bobj" />
</constructor-arg>
<property name="aobj">
<bean id="AAAobj" class="com.chirag.Spring.A"> <!-- Inner bean define here !-->
<constructor-arg>
<value>77712</value>
</constructor-arg>
<constructor-arg value="Hi Ok"/>
</bean>
</property>
</bean>
</beans>
Note:- you can't re-use of Inner bean.
How is dependency injection working?
* .The bean factory instantiates all objects. It parses your configuration (xml or annotations), instantiates your beans and sets their dependencies. Then all these beans are stored in the application context.
* .You usually have an entry point to your application - there you do
context.getBean(..)
. Now that bean has its dependencies injected, because it is put in the context by the bean factory.
* .The rule of thumb that will probably clear things: you never use the
new
operator (with bean classes) when using a DI framework. The framework makes the instances, not you.
* . We use Dependency Injection (DI) to implement loose coupling. The choice of any particulary DI Container is not that important.
* .Every time you create an instance of a class by using the
new
keyword, you tightly couple your code to that class, and you will not be able to substitute that particularl implementation with a different one (at least not without recompiling the code). Q . Are Spring Beans Thread Safe?
Answer : No.
Spring has different bean scopes (e.g. Prototype, Singleton, etc.) but all these scopes enforce is when the bean is created. For example a "prototype" scoped bean will be created each time this bean is "injected", whereas a "singleton" scoped bean will be created once and shared within the application context. There are other scopes but they just define a time span (e.g. a "scope") of when a new instance will be created.
The above has little, if anything to do with being thread safe, since if several threads have access to a bean (no matter the scope), it would only depend on the design of that bean to be or not to be "thread safe".
The reason I said "little, if anything" is because it might depend on the problem you are trying to solve. For example if you are concerned whether 2 or more HTTP requests may create a problem for the same bean, there is a "request" scope that will create a new instance of a bean for each HTTP request, hence you can "think" of a particular bean as being "safe" in the context of multiple HTTP requests. But it is still not truly thread safe by Spring since if several threads use this bean within the same HTTP request, it goes back to a bean design (your design of a bean backing class).
Q . How to Make/Design a Thread Safe "Object"?
Answer : There are several ways, probably too long to list here but here are a few examples:
Design your beans immutable: for example have no setters and only use constructor arguments to create a bean. There are other ways, such as Builder pattern, etc..
Design your beans stateless: for example a bean that does something can be just a function (or several). This bean in most cases can and should be stateless, which means it does not have any state, it only does things with function arguments you provide each time (on each invocation)
Design your beans persistent: which is a special case of "immutable", but has some very nice properties. Usually is used in functional programming, where Spring (at least yet) not as useful as in imperative world, but I have used them with Scala/Spring projects.
Design your beans with locks [last resort]: I would recommend against this unless you are working on a lower level library. The reason is we (humans) are not good thinking in terms of locks. Just the way we are raised and nurtured. Everything happens in parallel without us needing to "put that rain on pause, let me get an umbrella". Computers however are all about locks when you are talking "multiple things at the same time", hence there are some of us (exceptional people) who are doing their fair share and implementing libraries based on these locks. Most of other humans can just use these libraries and worry not about concurrency.
What is the difference between Bean Factory and Application Context?
On the surface, an application context is same as a bean factory. But application context offers much more.
► Application contexts provide a means for resolving text messages, including support for i18n of those messages.
► Application contexts provide a generic way to load file resources, such as images.
► Application contexts can publish events to beans that are registered as listeners.
► Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.
► ResourceLoader support: Spring�s Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances.
► MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.
What is the typical Bean life cycle in Spring Bean Factory Container?
The spring container finds the beans definition from the XML file and instantiates the bean.
► Using the dependency injection, spring populates all of the properties as specified in the bean definition
► If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean's ID.
► If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
► If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.
► If an init-method is specified for the bean, it will be called.
► Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
What do you mean by Auto Wiring?
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes.
no
► byName
► byType
► constructor
► autodetect.
What is XMLBeanFactory?
BeanFactory has many implementations in Spring. But one of the most useful one is org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. To create an XmlBeanFactory, pass a java.io.InputStream to the constructor. The InputStream will provide the XML to the factory. For example, the following code snippet uses a java.io.FileInputStream to provide a bean definition XML file to XmlBeanFactory.
Explain Bean lifecycle in Spring framework?
1. The spring container finds the beans definition from the XML file and instantiates the bean.
2. Using the dependency injection, spring populates all of the properties as specified in the bean definition.
3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the beans ID.
4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
5. If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.
6. If an init-method is specified for the bean, it will be called.
7. Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
How to integrate your Struts application with Spring?
To integrate your Struts application with Spring, we have two options:
► Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their dependencies in a Spring context file.
► Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a getWebApplicationContext() method.
What is IOC or inversion of control?
As the name implies 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. This concept is known as dependency injection because all object dependency (resources) is injected into it by framework.
Example:
<bean id="createNewStock" class="springexample.stockMarket.CreateNewStockAccont">
<property name="newBid"/>
</bean>
In this example CreateNewStockAccont class contain getter and setter for newBid and container will instantiate newBid and set the value automatically when it is used. This whole process is also called wiring in Spring and by using annotation it can be done automatically by Spring, refereed as auto-wiring of bean in Spring.
No comments:
Post a Comment