导入Spring框架
必须Jar包:
- commons-logging
- spring-beans
- spring-context
- spring-core
- spring-expression
常用Jar包:
- spring-aop
Maven:
org.springframework
spring-context
spring.versionorg.aspectjaspectjrt
{aspectj.version}
org.aspectj
aspectjweaver
${aspectj.version}
创建spring-context.xml配置文件
模版(不使用注解):
<?xml version="1.0" encoding="UTF-8"?>
<beans 1xmlns="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">
</beans>
模版(使用注解):
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
获取ApplicationContext上下文对象
// 已过时
BeanFactory factory = new ClassPathXmlApplicationContext("spring-context");
// 最常使用的
ApplicationContext context = new ClassPathXmlApplicationContext("spring-context");
// 如果xml文件太大,想分成多个xml文件,可以传入文件名数组
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring-context.xml",""});
区别:
BeanFactory:
- 尽可能晚的初始化Bean,适用于对内存要求很高的应用
ApplicationContext:
- BeanFactory功能的延伸
- 尽可能早的初始化Bean
- 支持国际化
- 支持事件监听机制
- 提供通用的方式获取资源