As of now we have ApplicationContext in main class because
nowhere else require to use getBean configuration. There are some scenarios
where we require ApplicationContext in dependent classes and we can access ApplicationContext
by implementing ApplicationContextAware interface.
ApplicationContextAware interface provide to know context
information like context aware (Know where you live).
BeanNameAware interface provide to know bean information
like name aware (know who you are).
DrawingApp.java
package org.yash.watertechsol;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawingApp {
public
static void main(String[] args){
ApplicationContext
context = new ClassPathXmlApplicationContext("spring.xml");
Triangle
triangle = (Triangle)context.getBean("triangle");
triangle.draw();
}
}
Triangle.java
package org.yash.watertechsol;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class Triangle implements ApplicationContextAware, BeanNameAware
{
private Point pointA;
private Point pointB;
private Point pointC;
private
ApplicationContext context = null;
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("Point A
= (" + getPointA().getX()+", "+getPointA().getY()+")");
System.out.println("Point B
= (" + getPointB().getX()+", "+getPointB().getY()+")");
System.out.println("Point C
= (" + getPointC().getX()+", "+getPointC().getY()+")");
}
@Override
public void
setApplicationContext(ApplicationContext context)
throws BeansException
{
this.context = context;
Triangle t =
(Triangle)context.getBean("triangle");
t.draw();
}
@Override
public void setBeanName(String
beanName) {
System.out.println("BeanName:
"+beanName);
}
}
Point.java
package org.yash.watertechsol;
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;
}
}
No comments:
Post a Comment