Spring一个轻量级的控制反转IoC/DI依赖注入和面向切面AOP的开源容器框架
2018-07-31 09:58:15
  • 0
  • 0
  • 0
  • 0

XML的解析:

常见的有2种解析模型:SAX和DOM

常见的解析工具有:DOM4j/jdom/xpull...,SUN为了规范xml文件解析提出了JAXP规范(javax.xml.parsers)

<?xml version="1.0" encoding="UTF-8"?>

<beans>

<bean id="product" class="com.yan.test4.ProduceImpl"/>

</beans>

public class BeanFactory {

private static final Map<String, Object> map = new HashMap<String, Object>();

private BeanFactory() {

}

static {

try {

parseXML();

} catch (Exception e) {

e.printStackTrace();

}

}

public static Object getBean(String key) {

if (map.containsKey(key))return map.get(key); 额外获取了单例的效果

return null;

}

private static void parseXML() throws Exception {

SAXParserFactory fac = SAXParserFactory.newInstance();

SAXParser parser = fac.newSAXParser();

parser.parse("beans.xml", new DefaultHandler() {

@Override

public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {

if ("bean".equals(qName)) {

try {

String id = attributes.getValue("id");

String className = attributes.getValue("class");

Object obj = Class.forName(className).newInstance();

map.put(id, obj);

} catch (Exception e) {

throw new SAXException(e.getMessage());

}

}

}

});

}

}

Spring框架最重要是提供了以类似上面xml+BeanFactory的方式管理配置在xml文件中的受管Bean

Hello Spring

Spring的IoC容器将面向接口的编程代价降到了最低

1、添加jar包

spring-core spring-context spring-context-support spring-beans spring-expression(SpEL)

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context-support</artifactId>

<version>5.0.8.RELEASE</version>

</dependency>

2、定义核心配置文件,实际上文件名称没有规定,一般位于src根目录下,名称为applicationContext.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 id="produce" class="com.yan.test4.ProduceImpl"/>

</beans>

3、通过Spring获取配置的bean对象

Resource r = new ClassPathResource("applicationContext.xml");

BeanFactory fac = new XmlBeanFactory(r);

IProduce p=(IProduce) fac.getBean("produce");

System.out.println(p); 

 
最新文章
相关阅读