In spring basically to autowired the properties of the beans Autowire is used,but it also provide some annotations to autowiring. @Autowired annotation is define in org.springframework.beans.factory.annotation.Autowired .To understand that how it is use let see below example-
Directory Structure -
Class Tri.java
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="p" class="com.test.Point">
<property name="x" value="10"></property>
<property name="y" value="20"></property>
</bean>
<bean id="tri" class="com.test.Tri">
</bean>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"></bean>
</beans>
Output is-
Directory Structure -
Class Tri.java
package com.test;
import org.springframework.beans.factory.annotation.Autowired;
public class Tri {
Point p;
public Point getP() {
return p;
}
@Autowired
public void setP(Point p) {
this.p = p;
}
public void show()
{
System.out.println("x="+p.getX());
System.out.println("y="+p.getY());
}
}
Class Draw.javaimport org.springframework.beans.factory.annotation.Autowired;
public class Tri {
Point p;
public Point getP() {
return p;
}
@Autowired
public void setP(Point p) {
this.p = p;
}
public void show()
{
System.out.println("x="+p.getX());
System.out.println("y="+p.getY());
}
}
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Draw {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Tri t=(Tri) context.getBean("tri");
t.show();
}
}
Class Point.javaimport org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Draw {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Tri t=(Tri) context.getBean("tri");
t.show();
}
}
package com.test;
public class Point {
int x,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;
}
}
file Spring.xml-public class Point {
int x,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;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="p" class="com.test.Point">
<property name="x" value="10"></property>
<property name="y" value="20"></property>
</bean>
<bean id="tri" class="com.test.Tri">
</bean>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"></bean>
</beans>
Output is-
x=10
y=20
y=20
For Further Reading,
0 comments:
Post a Comment