什么是spring
spring是一个轻量级的DI/IOC和AOP容器的开源框架。
DI:Dependency Injection(依赖注入)
IoC:inverse of control(控制反转)
AOP: Aspect-Oriented Programming(面向切面编程)
DI指spring创建对象的过程中,将对象依赖属性(简单值,集合,对象)通过配置设置给该对象
IoC:控制反转,就是将原本在程序中手动创建对象的控制权交给spring容器来做。
AOP:aop采取横向抽取机制,将分散在各个地方的重复的代码提取出来,在编译运行时将这些代码应用到需要执行的地方。
导入依赖的jar包
使用spring,首先导入jar包
spring-core 使用spring的核心jar包
spring-context
spring-beans
commons-logging
创建配置文件
创建名为applicationContext.xml的配置文件,使用spring.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/name 给bean元素设定标识 id唯一,name不唯一
class 把哪一个类交给spring容器去管理
-->
<bean id="helloWorld" name="hello world helloWorld2,helloWorld3;helloWorld4" class="com.teng.HelloWorld" scope="prototype">
</bean>
<bean id = "hw" class="com.teng.HelloWorld" scope="prototype">
<!--
第二种形式,通过有参构造注入,前提:必须有有参构造
index 通过参数的索引注入
type 通过参数的类型注入
-->
<!-- <constructor-arg index="0" value="1"></constructor-arg>
<constructor-arg index="1" value="向阳"></constructor-arg>-->
<constructor-arg type="int" value="23"></constructor-arg>
<constructor-arg type="java.lang.String" value="菲菲"></constructor-arg>
测试类
package com.teng;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
@org.junit.Test
public void test1(){
//spring 从spring容器中获取对象
//读取spring配置文件,创建bean工厂
BeanFactory beanFactory = new ClassPathXmlApplicationContext("/applicationContext.xml");
HelloWorld hell = (HelloWorld) beanFactory.getBean("helloWorld");
HelloWorld hell1 = (HelloWorld) beanFactory.getBean("hello");
//HelloWorld hell2 = beanFactory.getBean(HelloWorld.class);
HelloWorld hell3 = beanFactory.getBean("hw",HelloWorld.class);
hell.sayHell();
}
}
beanFactory可以通过三种方法获取对象
1,beanFactory.getBean(“id名/name名”);通过bean名获取
2,beanFactory.getBean(对象.class);通过class获取
3,beanFactory.getBean(“id名/name名”,对象.class);通过name+class 官方推荐