通过xml文件向Spring容器注册组件
-
创建一个maven工程,导入依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.3.RELEASE</version> </dependency>项目目录结构:
-
新建类Person和beans.xml文件
@Data @NoArgsConstructor @AllArgsConstructor public class Person { private String name; private Integer age; }<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="person" class="com.example.bean.Person"> <property name="name" value="tom"/> <property name="age" value="20"/> </bean> </beans> -
运行测试
public static void main(String[] args) { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); Object person = applicationContext.getBean("person"); System.out.println(person); }控制台打印结果