1.什么是IOC
- 控制反转,把对象创建和对象之间的调用过程,交给Spring进行管理
- 使用IOC的目的:降低耦合度
2.IOC的底层原理
- XML解析、工厂模式、反射
3.IOC接口
-
IOC思想基于IOC容器完成,IOC容器底层就是对象工厂
-
Spring提供IOC容器实现的两种方式:(两个接口)
a) BeanFactory: IOC容器的基本实现,是Spring内部使用的接口,不提供开发人员使用。(注意:BeanFactory加载配置文件时不会创建对象,在获取(使用)对象时才会创建对象)
b) ApplicationContext: BeanFactory接口的子接口,提供更多更强大的功能,一般由开发人员进行使用。(注意:ApplicationContext加载配置文件时就会将配置文件中的对象进行创建) -
ApplicationContext接口的常用实现类
4.IOC操作之Bean管理
- 什么是Bean管理?
——Bean管理指的是两个操作:a) Spring创建对象;b) Spring注入属性 - Bean管理操作实现的两种方式
——a) 基于XML配置文件的方式;b) 基于注解的方式
4.1基于XML方式进行Bean管理
4.1.1创建对象
<!--配置Hello对象的创建,默认执行无参构造方法完成对象创建-->
<bean id="hello" class="com.yulong.pojo.Hello"></bean>
4.1.2注入属性
第一种注入方式:使用Set方法进行注入
// 创建要注入的属性及其对应的方法
public class Hello {
private String firstWord;
private String secondWord;
public void setFirstWord(String str) {
this.firstWord = str;
}
public void setSecondWord(String str) {
this.secondWord = str;
}
@Override
public String toString() {
return firstWord + " " + secondWord;
}
}
<!--配置Hello对象的创建-->
<bean id="hello" class="com.yulong.pojo.Hello">
<!--给属性注入值-->
<property name="firstWord" value="Hello"></property>
<property name="secondWord" value="world"></property>
</bean>
第二种注入方式:使用有参构造器进行注入
public class Book {
private String bookName;
private String bookAuthor;
public Book(String bookName, String bookAuthor) {
this.bookName = bookName;
this.bookAuthor = bookAuthor;
}
@Override
public String toString() {
return "Book{" +
"bookName='" + bookName + '\'' +
", bookAuthor='" + bookAuthor + '\'' +
'}';
}
}
<!--通过有参构造器创建对象并注入属性-->
<bean id="book" class="com.yulong.pojo.Book">
<constructor-arg name="bookName" value="《三国演义》"></constructor-arg>
<constructor-arg name="bookAuthor" value="罗贯中"></constructor-arg>
</bean>
set注入的简化,p名称空间注入
在配置文件中添加p名称空间
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置Hello对象的创建-->
<bean id="hello" class="com.yulong.pojo.Hello" p:firstWord="p_hello" p:secondWord="p_world"></bean>
注入空值和特殊字符
<bean id="hello" class="com.yulong.pojo.Hello">
<!--注入空值-->
<property name="firstWord">
<null/>
</property>
<!--注入特殊字符,把带特殊符号的内容写到CDATA中 使用结构 <![CDATA[ 内容 ]]> -->
<property name="secondWord">
<value><![CDATA[我是特殊字符@#$%^&*>><<等等]]></value>
</property>
</bean>
注入外部Bean
- 先创建两个类service和dao类
- 在service里调用dao里面的方法
- 在spring配置文件中进行配置
public class UserDaoImpl implements UserDao{
@Override
public void update() {
System.out.println("我是userDao!");
}
}
public class UserService {
//创建UserDao类型属性,生成set方法
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void fun(){
System.out.println("service调用userdao!");
userDao.update();
}
}
<bean id="userService" class="com.yulong.service.UserService">
<!--通过set方式注入userDao对象
name:类里面属性名称 ref:创建userDao对象bean标签的ID值
-->
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="com.yulong.dao.UserDaoImpl"></bean>
注入内部bean
- 一对多关系:部门和员工。一个部门有多个员工,一个员工属于一个部门。
- 在实体类之间表示一对多关系,员工表示所属部门,使用对象类型属性进行表示。
//部门类
public class Department {
private String name;
public void setName(String name) {
this.name = name;
}
}
// 员工类
public class Emp {
private String name;
private String gender;
private Department dept;
public void setName(String name) {
this.name = name;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setDept(Department dept) {
this.dept = dept;
}
}
- 在spring配置文件中进行配置
<bean id="emp" class="com.yulong.bean.Emp">
<property name="name" value="张三"></property>
<property name="gender" value="男"></property>
<!--这里内部注入bean 或者采用外部注入-->
<property name="dept">
<bean id="deptment" class="com.yulong.bean.Department">
<property name="name" value="外交部"></property>
</bean>
</property>
</bean>
级联赋值
- 第一种方式
<bean id="emp" class="com.yulong.bean.Emp">
<property name="name" value="张三"></property>
<property name="gender" value="男"></property>
<!--级联注入 注意与外部注入的区别-->
<property name="dept" ref="dept"></property>
</bean>
<bean id="dept" class="com.yulong.bean.Department">
<property name="name" value="税务局"></property>
</bean>
- 第二种方式:
// Emp类中需设置对象的get方法用来设值
public class Emp {
private String name;
private String gender;
private Department dept;
public Department getDept() {
return dept;
}
............
<bean id="emp" class="com.yulong.bean.Emp">
<property name="name" value="张三"></property>
<property name="gender" value="男"></property>
<!--级联注入 注意与外部注入的区别-->
<property name="dept" ref="dept"></property>
<property name="dept.name" value="我是第二种方式" ></property>
</bean>
<bean id="dept" class="com.yulong.bean.Department">
<property name="name" value="税务局"></property>
</bean>
Emp{name='张三', gender='男', dept=Department{name='我是第二种方式'}}
Process finished with exit code 0
xml注入集合属性
public class Demo01 {
private String[] array;
private List<String> list;
private Map<String, Integer> map;
private Set<String> set;
public void setArray(String[] array) {
this.array = array;
}
public void setList(List<String> list) {
this.list = list;
}
public void setMap(Map<String, Integer> map) {
this.map = map;
}
public void setSet(Set<String> set) {
this.set = set;
}
@Override
public String toString() {
return "Demo01{" +
"array=" + Arrays.toString(array) +
", list=" + list +
", map=" + map +
", set=" + set +
'}';
}
}
<bean id="demo" class="com.yulong.collection.Demo01">
<property name="array">
<array>
<value>array01</value>
<value>array02</value>
<value>array03</value>
</array>
</property>
<property name="list">
<list>
<value>list01</value>
<value>list02</value>
<value>list03</value>
</list>
</property>
<property name="map">
<map>
<entry key="map01" value="1"></entry>
<entry key="map02" value="2"></entry>
</map>
</property>
<property name="set">
<set>
<value>set01</value>
<value>set02222</value>
<value>set02222</value>
</set>
</property>
</bean>
Demo01{array=[array01, array02, array03], list=[list01, list02, list03], map={map01=1, map02=2}, set=[set01, set02222]}
Process finished with exit code 0
在集合里设置对象类型值
public class Student {
private String name;
private List<Course> courseList;
public void setName(String name) {
this.name = name;
}
public void setCourseList(List<Course> courseList) {
this.courseList = courseList;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", courseList=" + courseList +
'}';
}
}
public class Course {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Course{" +
"name='" + name + '\'' +
'}';
}
}
<bean id="student" class="com.yulong.collection.Student">
<property name="name" value="张三"></property>
<property name="courseList">
<list>
<ref bean="course"></ref>
<ref bean="course"></ref>
</list>
</property>
</bean>
<bean id="course" class="com.yulong.collection.Course">
<property name="name" value="Spring"></property>
</bean>
<bean id="course2" class="com.yulong.collection.Course">
<property name="name" value="mabatis"></property>
</bean>
Student{name='张三', courseList=[Course{name='Spring'}, Course{name='Spring'}]}
集合注入部分提取出来
在Spring配置文件中引入名称空间util
<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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!--提取list集合类型属性注入-->
<util:list id="bookList">
<value>三国演义</value>
<value>水浒传</value>
<value>红楼梦</value>
</util:list>
<bean id="book01" class="com.yulong.collection.Book">
<property name="name" value="Book01"></property>
<property name="bookList" ref="bookList"></property>
</bean>
<bean id="book02" class="com.yulong.collection.Book">
<property name="name" value="Book02"></property>
<property name="bookList" ref="bookList"></property>
</bean>
Book{name='Book01', bookList=[三国演义, 水浒传, 红楼梦]}
Book{name='Book02', bookList=[三国演义, 水浒传, 红楼梦]}
4.2 FactoryBean
- Spring有两种类型bean,一种普通bean,另外一种工厂bean(FactoryBean)
- 普通bean:在配置文件中定义bean类型就是返回类型
- 工厂bean:在配置文件定义bean类型可以和返回类型不一样
a) 创建类,让这个类作为工厂bean,实现接口FactoryBean
b) 实现接口里面的方法,在实现的方法中定义返回的bean类型
public class MyBean implements FactoryBean<Course> {
@Override
public Course getObject() throws Exception {
Course course = new Course();
course.setName("factoryBean");
return course;
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return false;
}
}
<bean id="mybean" class="com.yulong.collection.MyBean"></bean>
@Test
public void Test01(){
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
Course mybean = context.getBean("mybean", Course.class);
System.out.println(mybean);
}
Course{name='factoryBean'}
4.3 Bean作用域
- 在spring里面,默认情况下,bean是单实例对象
- 在spring配置文件bean标签里面有属性(scope)用于设置单实例还是多实例
- Singleton和prototype
a) Singleton 单实例, prototype多实例
b) 设置scope值是Singleton时,加载spring配置文件时就会创建单实例对象
c) 设置scope值是prototype时,不是在加载配置文件时创建对象,而是在调用getBean方法时创建多实例对象
4.4 Bean生命周期
- 通过构造器创建bean实例(无参数构造)
- 为bean的属性设置值和对其他bean引用(调用set方法)
- 调用bean的初始化方法(需要进行配置初始化方法)
- bean的使用(对象获取到了)
- 当容器关闭时,调用bean的销毁方法(需要进行配置销毁的方法)
public class BeanEpoch {
public BeanEpoch() {
System.out.println("第一步:无参构造");
}
private String name;
public void setName(String name) {
this.name = name;
System.out.println("第二步:set方法");
}
public void initMethod(){
System.out.println("第三步:初始化方法");
}
public void destMethod(){
System.out.println("第五步:销毁方法");
}
}
<bean id="beanepoch" class="com.yulong.collection.BeanEpoch" init-method="initMethod" destroy-method="destMethod">
<property name="name" value="bean epoch"></property>
</bean>
@Test
public void test02(){
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
BeanEpoch beanepoch = context.getBean("beanepoch", BeanEpoch.class);
System.out.println("第四步:使用对象");
System.out.println(beanepoch);
context.close();
}
第一步:无参构造
第二步:set方法
第三步:初始化方法
第四步:使用对象
com.yulong.collection.BeanEpoch@175b9425
第五步:销毁方法
Process finished with exit code 0
4.5 BeanPostProcessor的生命周期有七步
- 通过构造器创建bean实例(无参数构造)
- 为bean的属性设置值和对其他bean引用(调用set方法)
- postProcessBeforeInitialization
- 调用bean的初始化方法(需要进行配置初始化方法)
- postProcessAfterInitialization
- bean的使用(对象获取到了)
- 当容器关闭时,调用bean的销毁方法(需要进行配置销毁的方法)
public class BeanPost implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("post processor before");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("post processor after");
return bean;
}
}
<bean id="postprocessor" class="com.yulong.collection.BeanPost"></bean>
第一步:无参构造
第二步:set方法
post processor before
第三步:初始化方法
post processor after
第四步:使用对象
com.yulong.collection.BeanEpoch@21b2e768
第五步:销毁方法
4.6 xml实现自动装配
- bean标签属性autowire配置自动装配(几乎不用都是用注解替代)
- autowire属性常用两个值:
a) byName根据属性名称注入,注入bean的ID值和类属性名称一样
b) byType根据属性类型注入
4.7 基于注解的方式进行bean管理
- 什么是注解:
a) 注解是代码特殊标记,格式:@注解名称(属性名称=属性值,…)
b) 注解作用在类上面,方法上面,属性上面
c) 使用注解的目的,简化xml配置 - Spring针对bean管理中创建对象提供注解:@Component @Service @Controller @ Repository
上面四个注解功能一样,都可以用来创建bean实例
添加context命名空间,并开启组件扫描,并查看当前spring版本是否需要导入spring-aop的包
<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:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:component-scan base-package="com.yulong.annotation"></context:component-scan>
value默认是类名称首字母小写,相当用使用xml管理时bean中的ID
@Service(value = "annUserService")
public class UserServiceAnn {
public void fun01() {
System.out.println("userService fun!!!");
}
}
@Test
public void test03(){
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
UserServiceAnn userService01 = context.getBean("annUserService", UserServiceAnn.class);
UserServiceAnn userService02 = context.getBean("annUserService", UserServiceAnn.class);
System.out.println(userService01);
System.out.println(userService02);
userService01.fun01();
}
默认是单例模式
com.yulong.annotation.UserServiceAnn@60099951
com.yulong.annotation.UserServiceAnn@60099951
userService fun!!!
-----------------------------------------
加入scope注解来替换模式
@Service(value = "annUserService")
@Scope("prototype")
public class UserServiceAnn {
public void fun01() {
System.out.println("userService fun!!!");
}
}
------------------
com.yulong.annotation.UserServiceAnn@5ab956d7
com.yulong.annotation.UserServiceAnn@3646a422
userService fun!!!
4.8 基于注解方式实现属性注入
- @Autowired :根据属性类型进行自动装配
- @Qualifier : 根据属性名称进行注入,需搭配@Autowired进行使用
- @Resource:可以根据类型注入,也可以根据名称注入。但是其是在javax包中,不推荐使用。
- @Value:注入普通类型属性。
@Repository
public class UserDaoImpl implements UserDao01{
@Override
public void fun01() {
System.out.println("UserDao01 fun01!!!");
}
}
@Service
public class UserService {
@Autowired
private UserDao01 userDao01;
public void fun02(){
System.out.println("User service!!!");
userDao01.fun01();
}
}
@Repository(value = "us0000")
public class UserDaoImpl implements UserDao01{
@Override
public void fun01() {
System.out.println("UserDao01 fun01!!!");
}
}
@Service
public class UserService {
@Autowired
@Qualifier("us0000")
private UserDao01 userDao01;
@Value("value annotation!!!")
private String str;
public void fun02(){
System.out.println(str);
System.out.println("User service!!!");
userDao01.fun01();
}
}
4.9 完全注解开发
@Configuration // 作为配置类,替代xml配置文件
@ComponentScan(basePackages = {"com.yulong"})
public class SpringConfig {
}
@Test
public void test02(){
ApplicationContext context =
new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService = context.getBean("userService", UserService.class);
userService.fun02();
}