类:Person
public class Person {
private String name;
private int age;
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;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
xml配置Bean
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--Spring XML配置方式 配置Bean-->
<bean id="person" name="person" class="com.demo.po.Person">
</beans>
测试类:Junit4Test - 使用Junit4进行单元测试
public class Junit4Test {
private ApplicationContext context = null;
@Before
public void before() {
System.out.println("before");
//加载容器
context = new ClassPathXmlApplicationContext("applicationContext_xml.xml");
}
@Test
public void method() {
//获取对象
Person person = (Person) context.getBean("person");
//打印
System.out.println(person);//结果:Person{name='null', age=0}
}
}
Spring xml配置方式配置 Bean
最新推荐文章于 2024-07-11 08:34:25 发布
本文详细探讨了Spring框架中XML配置Bean的方式,包括如何声明Bean、注入依赖以及配置初始化和销毁方法。通过实例解析,阐述了XML配置文件的结构和重要元素,帮助读者掌握Spring XML配置的核心概念。
摘要由CSDN通过智能技术生成