定义一个Student 类(包括id ,name,age等),在XML中配置为Bean,分别使用id方式、类类型方式获取该Bean
时间: 2024-05-07 19:21:53 浏览: 15
下面是一个示例代码:
```java
public class Student {
private int id;
private String name;
private int age;
// 构造函数
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
// getter 和 setter 方法
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
```
然后,在 XML 配置文件中定义该 Bean,示例如下:
```xml
<bean id="student" class="com.example.Student">
<property name="id" value="1" />
<property name="name" value="Tom" />
<property name="age" value="18" />
</bean>
```
在 Java 代码中,我们可以使用 id 方式获取该 Bean:
```java
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getId() + " " + student.getName() + " " + student.getAge());
```
也可以使用类类型方式获取该 Bean:
```java
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = context.getBean(Student.class);
System.out.println(student.getId() + " " + student.getName() + " " + student.getAge());
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)