1、编写一个Circle类,有成员变量半径r,成员方法getArea()和getLength(),分别求面积和周长。 2、通过Spring实例化一个bean,并注入属性值 3、编写test类,输出圆的面积和周长。
时间: 2024-05-01 12:22:52 浏览: 91
1. Circle类代码如下:
```java
public class Circle {
private double r;
public Circle(double r) {
this.r = r;
}
public double getArea() {
return Math.PI * r * r;
}
public double getLength() {
return 2 * Math.PI * r;
}
}
```
2. Spring配置文件(假设文件名为applicationContext.xml)如下:
```xml
<beans>
<bean id="circle" class="Circle">
<constructor-arg value="5"/>
</bean>
</beans>
```
3. Test类代码如下:
```java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Circle circle = (Circle) context.getBean("circle");
System.out.println("Circle area: " + circle.getArea());
System.out.println("Circle length: " + circle.getLength());
}
}
```
运行Test类的输出结果应该是:
```
Circle area: 78.53981633974483
Circle length: 31.41592653589793
```
阅读全文