Spring基于XML方式进行容器配置
2018-02-23 本文已影响45人
乐傻驴
传统上,配置元数据是以简单直观的XML
格式提供的
定义UserService类
/**
* @author SanLi
* Created by 2689170096@qq.com/SanLi
*/
public class UserService {
/**
* 添加用户
*/
public void add() {
System.out.println("调用add()方法。。");
}
}
XML配置:
在类路径下或者计算机磁盘位置定义spring-config.xml
配置文件
<?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-->
<bean id="userService" class="com.sample.UserService"/>
</beans>
id属性是一个用来标识单个bean定义的字符串。class属性定义了bean的类型并使用完全限定的类名。
实例化容器
创建ClassPathXmlApplicationContext
或FileSystemXmlApplicationContext
的实例,提供给构造函数配置文件位置,它允许容器从各种外部资源(比如本地文件系统、Java
类路径)加载配置。
从类路径获取上下文配置文件
public static void main(String[] args) {
/*从类路径获取上下文配置文件*/
ApplicationContext xmlApplicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
/*根据XML配置的ID值获取Bean*/
UserService userService = (UserService) xmlApplicationContext.getBean("userService");
/*调用add()方法*/
userService.add();
}
从文件系统或URL中获取上下文定义文件
public static void main(String[] args) {
/*从文件系统或URL中获取上下文定义文件*/
ApplicationContext fileApplicationContext = new FileSystemXmlApplicationContext("F:/spring-config.xml");
/*根据XML配置的ID值获取Bean*/
UserService userService = (UserService) fileApplicationContext.getBean("userService");
/*调用add()方法*/
userService.add();
}
博客原文地址:基于XML方式进行容器配置