版权声明: https://blog.csdn.net/qq_38386316/article/details/88604945
1.注入对象
- DrawingApp.java
package org.zcs.spring;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class DrawingApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
//BeanFactory factory = new FileSystemXmlApplicationContext("src/spring.xml");
//Triangle triangle = new Triangle();
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Triangle triangle = (Triangle)context.getBean("triangle");
triangle.draw();
}
}
- Triangle.java
package org.zcs.spring;
public class 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("This is Point A: (" +getPointA().getX() +"," + (getPointA().getY()) +")");
System.out.println("This is Point B: (" +getPointB().getX() +"," + (getPointB().getY()) +")");
System.out.println("This is Point C: (" +getPointC().getX() +"," + (getPointC().getY()) +")");
}
}
- Point.java
package org.zcs.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;
}
}
- spring.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id = "triangle" class= "org.zcs.spring.Triangle" >
<property name="pointA" ref = "zeroPoint"></property>
<property name="pointB" ref = "twoPoint"></property>
<property name="pointC" ref = "threePoint"></property>
</bean>
<bean id= "zeroPoint" class = "org.zcs.spring.Point">
<property name="x" value = "0"></property>
<property name="y" value = "0"></property>
</bean>
<bean id= "twoPoint" class = "org.zcs.spring.Point">
<property name="x" value = "20"></property>
<property name="y" value = "0"></property>
</bean>
<bean id= "threePoint" class = "org.zcs.spring.Point">
<property name="x" value = "20"></property>
<property name="y" value = "0"></property>
</bean>
</beans>
2.学习笔记
- 学习了如何使用bean将对象赋值并注入数据,
- 再注入对象,得出相应的数值。