编写有属性id和name的类Teacher,用标签<bean>配置为spring的bean。在测试程序中读取该属性并输出
时间: 2024-03-15 19:46:32 浏览: 45
好的,我明白了。下面是代码示例:
Teacher类的定义:
```
public class Teacher {
private int id;
private String name;
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
```
在Spring的配置文件中,使用`<bean>`标签配置Teacher类的bean:
```
<bean id="teacher" class="com.example.Teacher">
<property name="id" value="123"/>
<property name="name" value="张三"/>
</bean>
```
然后,在测试程序中,我们可以通过Spring的容器获取Teacher对象,并输出其属性值:
```
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Teacher teacher = (Teacher) context.getBean("teacher");
System.out.println("Teacher id: " + teacher.getId());
System.out.println("Teacher name: " + teacher.getName());
}
```
运行程序后,输出结果如下:
```
Teacher id: 123
Teacher name: 张三
```
阅读全文