Spring初见
~~~~~~~~~
1,导入相关jar包(beans/core);
2,导入依赖包(common-logging)
3,配置XML文件(作用:告诉spring帮我管理哪些bean);
1)在classpath下,application.xml/applicationContext.xml;
2)<beans><bean id="" class="" /></beans>
4,使用容器:
1)创建一个资源文件对象(ClasspathResource);
2)创建一个BeanFactory(Spring的容器);创建一个基于XML的BeanFactory:XmlBeanFactory,传入XML配置文件资源对象;
3)从容器中获取对象:
1. getBean(Class cls):按照类型获取bean;
2. getBean(String name):按照名字获取bean;
3. getBean(String name, Class cls):按照名字和类型获取;
~~~~~~~~~~~~~
Spring的加载过程
~~~~~~~~~~~~~
1,找到对应的配置文件(xml);
2,加载配置文件;
3,解析所有的bean元素;识别id和class属性;
4,通过反射创建一个这个类型对应的实例;
5,把id作为key,把实例作为value存到spring容器中;
6,getBean从容器中获取到创建好的对象的实例;
~~~~~~~~~~~~~~~
import分散配置信息
~~~~~~~~~~~~~~~
在总配置文件中使用`import`元素导入各个模块的配置文件信息(Struts2中我们使用 `include`导入)
其中可以使用两种预定义的前缀,这两种方式同样适用于其他的资源路径查找,分别是:
1, classpath:
2, file
xml里面配置:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://www.springframework.org/schema/beans 4 http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 6 <bean id="helloSpring" class="com.shreker.spring.kp01_hellospring.Hello" /> 7 <!-- 8 id:全局必须唯一 9 name: 可以给这个类型定义多个别名(alias),多个名字之间需要使用英文逗号隔开 10 并且可以使用Factory的getAliases()方法获取, 11 一般在SpringMVC中使用(相当于url-pattern,多个可使用时空格隔开,SpringMVC中讲解) 12 --> 13 14 </beans>
测试类里面:
1 package com.shreker.spring.kp01_hellospring; 2 3 import org.junit.Test; 4 import org.springframework.beans.factory.BeanFactory; 5 import org.springframework.beans.factory.xml.XmlBeanFactory; 6 import org.springframework.core.io.ClassPathResource; 7 import org.springframework.core.io.Resource; 8 9 @SuppressWarnings("deprecation") 10 public class HelloTest { 11 12 @Test 13 public void testTest() throws Exception { 14 Resource resource = new ClassPathResource("application.xml"); 15 BeanFactory factory = new XmlBeanFactory(resource); 16 IHello h = factory.getBean("helloSpring", IHello.class); 17 h.hello(); 18 } 19 20 }
基于Spring测试的使用:
1, 首先导入基础测试需要的jar: test,aop,expression,context
2, 在测试类上编写标签 @RunWith(SpringJUnit4ClassRunner.class)
表示给Spring给JUnit提供了一个运行环境,其实Spring内部会把当前的测试类当作Spring的一个bean处理
如此, Spring就可以在测试文件启动的时候,自动的启动Spring容器
3, 在@RunWith相同的位置添加注解:@ContextConfiguration, 参数填写包含后缀的本模块的xml配置文件的名称
这个参数可以不写, 但是如果不写,则需要按照约定的方式给配置文件起名,这个约定的配置文件名的格式是:
`TestClassName-context.xml`
4, 在测试类中编写一个BeanFactory的字段,并使用注解@Autowired标注
表示告诉Spring这个字段就是你默认需要创建的BeanFactory
这个就是DI:Dependency Injection 依赖注入