Friday, October 2, 2015

Spring Framework - 10


________________________________________________________

Implement ApplicationContextAware to access object variables from "Triangle" class. This implements a method to setApplicationContext(ApplicationContext context) , that gives access to the context to modify Object variables of "Triangle class

BeanAwareContext is implemented to find teh name of the Bean Class(down in the implemeneted setter method)

_________________________________________________________

Spring annotations

@Required : is an indication on nullpointer variables.. if they are not declared within the spring.xml, while their values are used in some related methods. This turns out to be useful, as it throws an exception during the BeanPostProcessing itself, instead of a scenario where the code accesses the method at a later stage of the application.
1)
@Required is placed over a variable declaration or the variables setter method, in the object class. 
2)
<bean class= "org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor">
</bean>


@Autowired
  • Holds same functionaly as the "autowire" parameter in the <bean> tag.
  • It first autowires the class object beanvariables based on type, then name and then the qualifier(refer annotation below)
  • Since it autowires by type first, and if there and many <bean> with same "class", then it then looks for the name of the beans as in match to teh variable names in the class, However, in cases where more than 2 classes use the same bean with different variable names, then we also include another annotation called @qualifier. Refer the next anotation for the same.

This is also placed over a variable declaration or the variables setter method, in the object class. 
1)
@Autowired is placed over a variable declaration or the variables setter method, in the object class. 
2)
<bean class= "org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">
</bean>


@Qualifier("qualifiername")
Refer @Autowire Annotation to understand this one better. This is also placed right below the @autowire annotation, which in-turn is being placed over a variable declaration or the variables setter method, in the object class. 
1)
@Qualifier("testQualifier") is placed UNDER the @autowire in the object class for additional reference help to identify the right bean
2)
<bean class= "org.springframework.beans.factory.annotation.QualifierAnnotationBeanPostProcessor">
</bean>
3)include a <qualifier> tag
<beans>
<bean id=".." class="...">
<qualifier value="testQualifier" />
<property name="x" value="someValue" />
<bean>
<bean class= "org.springframework.beans.factory.annotation.QualifierAnnotationBeanPostProcessor">
</bean>
</beans>


NOTE:
  • step 2) for all the annotations can be skipped and simply replaced with just one line, in the spring.xml
    • <context:annotation-config/>
  • adding a <qualifier> tag can bring in other related xml exceptions.. hence... copy and paste xml namespaces at the beginning of the spring.xml
    • comment the default<DOC.... tag
    • replace <beans> tag with the below content
<!-- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> -->

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:websocket="http://www.springframework.org/schema/websocket"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd">
<bean ..............................> </bean>
</beans>


Stereotype Annotations:
Configured in spring.xml as below:
  • <context:component-scan base-package= "<<javaPackageName>>"/>
Note:
including the above tag enables a scan for all the annotations below within the <<javaPackageName>>

@Component(org.springframework.stereotype.Component)
@Service(org.springframework.stereotype.Service)
@Repository(org.springframework.stereotype.Repository)
@Controller(org.springframework.stereotype.Controller)



External Annotations used in Spring framework
(JSR-250)annotations- standard annotations across multiple technologies, also used here.

  1. @Resource(javax.annotation.Resource) - used as @autowire 
    • @Resource (or) @Resource(resourceName")
  2. @PostConstruct(javax.annotation.Resource) - placed above a method treats it like a init() method(same method as the init() method created for execution of logic just after bean creation)
  3. @PreDestroy(javax.annotation.Resource) - placed above a method treats it like a destroy() method(same method as the destroy() method created for execution of logic just before bean destroyed).
    • As discussed earlier, Replacing of AbstractApplicationContext class and call to registerShutdownHook is required  only while implementing destroy annotation.
  4. @Component
________________________________________________________



Using Properties file for Strings externalizing: ResourceBundleMessageSource
  • This is used to access string values from a properties file within a class file
Done is 3 steps:
1)Create a .properties file with required string and relevant values in the src location of teh project. 2)Configure the ResourceBundleMessageSource withing the spring.xml with a specific "id" as below:
.... <bean id="" class=".....ResourceBundleMessageSource">
<property>.....</property> // for multiple properties files.
.....

3)Now access this message source using context as below :
......context.getMessage(....); 
4)Now, to make it available for any object.. we need to declare it as a local variable with the object class with the same name as "id"(in spring.xml) and provide its gettign and seetter.. n access it with the getter method of the object.

..............
Also consider accessing dyamic paceholders within the .properties files.. later passed as messages ot the messageSource in class.
........

________________________________________________________

EVENT HANDLING in Spring Framework

org.springframework.context.

ApplicationListener(using ApplicationEvent as input)
/ApplicationEventPublisher
/ApplicationEventPublisherAware

1)Publishing Application Events
  • Create a class that implement ApplicationListener and implement its unimplemented method(onApplicationEvent(ApplicationEvent event), which gets executed when the event occurs. Once this is done, this class listens to all events published on Spring framework.
  • Configure this as a bean in the spring.xml; either by manually entereing the <bean> tag for this newly created class (OR) simply include @Component annotation above the class declaration, which does the same function. 
2)Publishing Custom ApplicationEvent that gets listened and published when a method that is desired to be published when executed, executes..
  • create a customEvent class  that extends ApplicationEvent and overwrite the toString() method
  • Now publish this event(say, you want to publish the execution of Draw method in the Shape class. For this you need to do the following steps:
    • Implement ApplicationEventPublisherAware and implement the local variable ApplicationEventPublisher in the unimplemented setter method in the Shape class that has the draw() method.
    • Now, define the Event you just created(customEvent) and pass this event to the publisher as below in the draw() method:
    • ... draw(){ .... CustomEvent ce = new CustomEvent(); publisher.publishEvent(ce);}
  • Now, when draw() method is called everytime, the toString() of CustomEvent is executed too.
________________________________________________________

Spring Framework- 9 - autowiring

Autowiring is a technique of the spring framework to automate the initiation of the bean Class variables without actually defining them within the bean tags.
(also refer autowiring performed using Annotations, in the later links)

Let's say, class Triangle with 3 Point variables as below,

public class Triangle {

public Triangle() {
}

private Point pointA;
private Point pointB;
private Point pointC;
public Point getPointA() {
return pointA;
}

public void setPointA(Point pointA) {
this.pointA = pointA;
}

public Point getPointB() {
return pointB;
}

public void setPointB(Point pointB) {
this.pointB = pointB;
}

public Point getPointC() {
return pointC;
}

public void setPointC(Point pointC) {
this.pointC = pointC;
}

public void Draw()
{
System.out.println("PointA: (" + getPointA().getX() + "," + getPointA().getY()+")");
System.out.println("PointB: (" + getPointB().getX() + "," + getPointB().getY()+")");
System.out.println("PointC: (" + getPointC().getX() + "," + getPointC().getY()+")");
}
}

The respective spring.xml would be as below:

<beans>
<bean id="triangle" class="com.product.springDemo.Triangle">
<property name="pointA" ref="Bean-pointA"/>
<property name="pointB" ref="Bean-pointB"/>
<property name="pointC" ref="Bean-pointC"/>
</bean>
<bean id="Bean-pointA" class="com.product.springDemo.Point">
<property name="x" value="20"/>
<property name="y" value="200"/>
</bean>
<bean id="Bean-pointB" class="com.product.springDemo.Point">
<property name="x" value="20"/>
<property name="y" value="200"/>
</bean>
<bean id="Bean-pointC" class="com.product.springDemo.Point">
<property name="x" value="30"/>
<property name="y" value="300"/>
</bean>
</beans>

However, using autowire makes it relatively simpler as below,



All we need to do is to just add a "autowire" attribute to the <bean> tag.
autowire attribute has 3 values:

  1. byName - tries to find a match of the Triangle class variable with each of the defined <bean id=" attribute. and if there's a match, the variable is initialised.
  2. constructortries to find a match of the Triangle class Contructor parameters variable with each of the defined <bean id=" attribute. and if there's a match, the variable is initialised.
  3. byTypetries to find a match of the Triangle class variable with each of the defined <bean class=" attribute. and if there's a match, the variable is initialised.
  4. default
  5. Autodetect
  6. no -  autowiring is deactivated
<beans>
<bean id="triangle" class="com.findgoose.springDemo.Triangle" autowire="byName ">
</bean>
<bean id="pointA" class="com.product.springDemo.Point">
<property name="x" value="10"/>
<property name="y" value="100"/>
</bean>

<bean id="pointB" class="com.product.springDemo.Point">
<property name="x" value="20"/>
<property name="y" value="200"/>
</bean>

<bean id="pointC" class="com.product.springDemo.Point">
<property name="x" value="30"/>
<property name="y" value="300"/>
</bean>
<alias name="triangle" alias="threeSided"/>
</beans>

Spring Framework - 8 - Collection tags


Supported collections are:
  1. <list>
  2. <set>
  3. <map>
---------------------------------------------------------------------




1. <list>

    • DrawingApp class remains the same, however refering to the Triangle Collection bean this time as below.

public class DrawingApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
TriangleCollection triangleCollection = (TriangleCollection)      context.getBean("triangleCollection");
triangleCollection.Draw();
}
}

    • New Triangle class, TriangleCollection modified for accepting List for Point objects as shown below
public class TriangleCollection {

private List<Point> pointsList;

public List<Point> getPointsList() {
return pointsList;
}

public void setPointsList(List<Point> pointsList) {
this.pointsList = pointsList;
}

public void Draw()
{
for(Point point: pointsList)
{
System.out.println("Point: (" + point.getX() + "," + point.getY()+")");
}
}
}


    • The spring.xml would be modified as below. The<ref> tags are used within <list> tags with the bean attribute to initiate the Point objects form within the "triangleCollection" bean.

<beans>
        <bean id="triangleCollection" class="com.product.springDemo.TriangleCollection">
<property name="pointsList">
<list>
<ref bean ="Bean-pointB"/>
<ref bean ="Bean-pointC"/>
</list>
</property>
</bean>
<bean id="Bean-pointB" class="com.product.springDemo.Point">
<property name="x" value="20"/>
<property name="y" value="200"/>
</bean>
<bean id="Bean-pointC" class="com.product.springDemo.Point">
<property name="x" value="30"/>
<property name="y" value="300"/>
</bean>
        </beans>


--------------------------------------------------------------------
2. <set>

  • DrawingApp class remains the same as above
  • New Triangle class, TriangleCollection modified for accepting Set for Point objects as shown below
public class TriangleCollection {

private Set<Point> pointsList;

public Set<Point> getPointsList() {
return pointsList;
}

public void setPointsList(Set<Point> pointsList) {
this.pointsList = pointsList;
}

public void Draw()
{
for(Point point: pointsList)
{
System.out.println("Point: (" + point.getX() + "," + point.getY()+")");
}
}
}



  • The spring.xml would be modified as below. The<ref> tags are used within <set> tags with the bean attribute to initiate the Point objects form within the "triangleCollection" bean.

<beans>
        <bean id="triangleCollection" class="com.product.springDemo.TriangleCollection">
<property name="pointsList">
<set>
<ref bean ="Bean-pointB"/>
<ref bean ="Bean-pointC"/>
</set>
</property>
</bean>
<bean id="Bean-pointB" class="com.product.springDemo.Point">
<property name="x" value="20"/>
<property name="y" value="200"/>
</bean>
<bean id="Bean-pointC" class="com.product.springDemo.Point">
<property name="x" value="30"/>
<property name="y" value="300"/>
</bean>
        </beans>

Spring Framework- 7 - Alias and idref tags

The <alias> tag is used to add an additional name to an existing bean, as show in the code below:

public class DrawingApp {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Triangle triangle = (Triangle) context.getBean("threeSided");
triangle.Draw();
}
}

while the <alias> tag is defined as below:

<bean id="triangle" class="com.project.springDemo.Triangle">
<property name="pointA">
<bean class="com.project.springDemo.Point">
<property name="x" value="10"/>
<property name="y" value="100"/>
</bean>
</property>
<property name="pointB" ref="Bean-pointB"/>
<property name="pointC" ref="Bean-pointC"/>
</bean>
<alias name="triangle" alias="threeSided"/>

</beans>

Note: the <alias> tag can be entirely replaced with the name attribute on the <bean> tag as below, However, this is not recommended.

<bean id="triangle" class="com.project.springDemo.Triangle" name="threeSided">

---------------------------------------------------------------------------------------------------

The idref attribute is used to handle exception when a referred bean isn't present in the respective xml

Usage is as below:

<beans>
<bean id="triangle" class="com.project.springDemo.Triangle">
<property name="pointA">
<bean class="com.project.springDemo.Point">
<property name="x" value="10"/>
<property name="y" value="100"/>
</bean>
</property>
<property name="pointB">
                    <idref="Bean-pointB"/>
  </property>
<property name="pointC" ref="Bean-pointC"/>
</bean>

<bean id="Bean-pointB" class="com.project.springDemo.Point">
<property name="x" value="20"/>
<property name="y" value="200"/>
</bean>
<bean id="Bean-pointC" class="com.project.springDemo.Point">
<property name="x" value="30"/>
<property name="y" value="300"/>
</bean>

<alias name="triangle" alias="threeSided"/>
</beans>

Spring Framework- 6 - InnerBeans

We could include innerbeans as shown in the code below:

<beans>
<bean id="triangle" class="com.findgoose.springDemo.Triangle">
<property name="pointA" ref="Bean-pointA">
<bean id="Bean-pointA" class="com.project.springDemo.Point">
<property name="x" value="10"/>
<property name="y" value="100"/>
</bean>
</property>
<property name="pointB" ref="Bean-pointB"/>
<property name="pointC" ref="Bean-pointC"/>
</bean>

<bean id="Bean-pointB" class="com.project.springDemo.Point">
<property name="x" value="20"/>
<property name="y" value="200"/>
</bean>
<bean id="Bean-pointC" class="com.project.springDemo.Point">
<property name="x" value="30"/>
<property name="y" value="300"/>
</bean>
</beans>

In the above code,

  • the ref tag and the id="Bean-pointA" tag is no more required.
  • pointA object can be embedded within the property tag of the "triangle" bean, in situations where it would be referred for instantiations only by the "triangle" bean. Which is why the above mentioned tags are no more needed either.

Thursday, October 1, 2015

Spring Framework - 5 - Injecting Object-Type Variables

In the previous blog , the class datatype variables are injected using the Spring framework. However, in this blog, we will be injecting Object-type variable using spring.

Let's say, Drawing App class still remains same,

public class DrawingApp {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
                Triangle triangle = (Triangle) context.getBean("triangle");
              triangle.Draw();
}
}

Create a new class Point, which is the intended class variable of object type, which we will be injecting using spring,

public class Point {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}


}

Let's now create the Triangle class, which has three Point variables defined in it which is of Object type, as below,

public class Triangle {

public Triangle() {
}
private String type;
private int height;

private Point pointA;
private Point pointB;
private Point pointC;
public Point getPointA() {
return pointA;
}

public void setPointA(Point pointA) {
this.pointA = pointA;
}

public Point getPointB() {
return pointB;
}

public void setPointB(Point pointB) {
this.pointB = pointB;
}

public Point getPointC() {
return pointC;
}

public void setPointC(Point pointC) {
this.pointC = pointC;
}
public void Draw()
{
System.out.println("PointA: (" + getPointA().getX() + "," + getPointA().getY()+")");
System.out.println("PointB: (" + getPointB().getX() + "," + getPointB().getY()+")");
System.out.println("PointC: (" + getPointC().getX() + "," + getPointC().getY()+")");
}

}


In order to inject these Object type class variables, in spring.xml
1)we need to define 3 Point beans as individual beans
2)refer the defined point beans as Variables of "triangle" bean using the "ref" attribute of <property> tag

as below,

<beans>
<bean id="triangle" class="com.project.springDemo.Triangle">
<property name="pointA" ref="Bean-pointA"/>
<property name="pointB" ref="Bean-pointB"/>
<property name="pointC" ref="Bean-pointC"/>
</bean>

<bean id="Bean-pointA" class="com.project.springDemo.Point">
<property name="x" value="10"/>
<property name="y" value="100"/>
</bean>
<bean id="Bean-pointB" class="com.project.springDemo.Point">
<property name="x" value="20"/>
<property name="y" value="200"/>
</bean>
<bean id="Bean-pointC" class="com.project.springDemo.Point">
<property name="x" value="30"/>
<property name="y" value="300"/>
</bean>
</beans>


Conclusion:
Though the 3 Point objects are initialized with their respective variable instantiations, there is only one reference initiation made to the Triangle class in the DrawingApp class which is the beauty of the Spring framework.

ie,
Triangle triangle = (Triangle) context.getBean("triangle");
              triangle.Draw();

Spring Framework - 4 - Injecting Datatype(bean/object) Variables

Now, how does it work with Class variables value setting using Spring?

This can happen at 2 levels in Spring,
1)Getter and Setter methods of the variable
2)Using Class Constructors.

The DrawingApp class remains the same,

public class DrawingApp {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
                Triangle triangle = (Triangle) context.getBean("triangle");
              triangle.Draw();
}
}

1)Lets look into the getters and setters of the variable Check the code below:

Implement 2 variables in Triangle class as below:

public class Triangle {

private String type;
private int height;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
        public void Draw() { 
                System.out.println(getType() + "Triangle Drawn"); 
                System.out.println(getHeight() + "is the height"); 
       }
}

Now, in order to set these variables using the spring framework, we need to implement the <property> tag in spring.xml as below:

<beans>
<bean id="triangle" class="com.project.springDemo.Triangle">
<property name="type" value="equilateral"/>
<property name="height" value="20"/>
</bean>
</beans>
note: There can be more than one bean tag within the beans tag.

And now, while executing the DrawingApp Class, the Spring framework uses the setters methods to set the values of the variables to the value attribute based on the name value of the <property> tag in spring.xml . Note: The value of the name attribute should be equal to the variable name in the POJO.

2)Lets look into the Constructor arguments way of setting variable. Check the code below:

Implement 2 variables in Triangle class along with constructors as below:

public class Triangle {
private String type;
private int height;
public Triangle(String type,int height) ------(a)
{
this.type = type;
this.height=height;
}

public Triangle(String type)-----------------(b)
{
this.type = type;
}
public String getType() {
return type;
}
// public void setType(String type) {
// this.type = type;
// }
public int getHeight() {
return height;
}
// public void setHeight(int height) {
// this.height = height;
// }
public void Draw()
{
System.out.println(getType() + " Triangle Drawn");
System.out.println(getHeight() + " is the height");
}
}
Note that the setters are no more required, as the spring framework uses the Constructors to set them in this scenario.
Now, in order to set these variables using the spring framework, we need to implement the <constructor-arg> tag in spring.xml :
some scenarios of using the <constructor-arg> are:
note: The name attribute is not there in this tag.

(i)----------Sets class variable using constructor (a)--------------------------------------------------
<beans>
<bean id="triangle" class="com.project.springDemo.Triangle">
<constructor-arg index="0" value="equilateral"/> 
  <constructor-arg index="1" value="20"/> 
</bean>
</beans>

(ii)----------Sets class variable using constructor (a), same as (i)-----------------------------------
<beans>
<bean id="triangle" class="com.project.springDemo.Triangle">
<constructor-arg type="java.lang.String" value="equilateral"/>
                <constructor-arg type="int" value="20"/> 
</bean>
</beans>

(iii)-------Sets class variable using constructor (b)-----------------------------------------------------
<beans>
<bean id="triangle" class="com.project.springDemo.Triangle">
<constructor-arg type="java.lang.String" value="equilateral"/>
</bean>
</beans>