一.概述
是一个java后台框架,主要用来整合其他框架
二.特点
1. IOC
控制反转,由Spring来创建对象,从Spring容器中获取对象
问题:
(1) Spring根据什么来创建对象?
答:有两种方式
a.配置文件中,配置<bean>标签
b.类上加注解 , 配置扫描包路径,
添加的注解有@Component,@Controller,@Service,@Repository若是多例则需要再加一个注解@
2.DI
依赖注入,spring创建对象时,初始化对象成员属性
问题:
(1)怎么初始化(变量初始值从哪里获取)?
答:两种
1.配置文件
2.属性上(或是set方法上)加注解
@Value 修饰普通属性
@Autowired 修饰类变量 根据类型自动装配(spring容器中要有对应的对象)
@Qualifier("springId名") 类型相同时,注入指定id的bean对象
@Autowired 修饰类变量 根据类型自动装配(spring容器中要有对应的对象)
@Qualifier("springId名") 类型相同时,注入指定id的bean对象
3.AOP
面向切面编程:可以增强方法
实现方式:(1)java动态代理(基于接口) (2)cglib(继承)
三 实例
配置文件applicationContext.xml 放在src下(类路径下):
1. 配置文件方式 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" xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloJava" class="com.blueSky.test.HelloJava">
<property name="content" value="你好,java" />
</bean>
<bean id="helloWorld" class="com.blueSky.test.HelloWorld">
<property name="content" value="你好,世界" />
<property name="helloJava" ref="helloJava"></property>
</bean>
</beans>
2. 注解方式 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" 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">
<!-- 下面的配置作用是指定spring扫描的包-->
<context:component-scan base-package="com.blueSky.annotation" />
</beans>