IOC操作Bean管理:什么是Bean管理? Bean管理的两种操作方式、bean的生命周bean分类:普通bean与工厂bean、bean的作用域、 bean引入外部属性文件

1. 什么是Bean管理?

  1. Spring操作对象
  2. Spring注入属性

2. Bean管理的两种操作方式

2.1 基于xml配置文件方式实现

2.1.1 基于xml方式创建对象

  • 在spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象的创建。
  • bean标签的常用属性:
  • id属性:给这个对象取一个标识
  • class属性:要创建对象的类的全路径
  • name:name与id作用一样,不同的是name中可以加特殊符号
  • 创建对象时,默认也是执行无参构造方法
<?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">
    <!--配置User对象创建-->
    <bean id="user" class="com.spring.spring5.User"></bean>
</beans>

2.1.2 基于xml方式注入属性

  • DI:依赖注入、就是注入属性
2.1.2.1 第一种注入方式:使用set方法
<?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="book" class="com.spring.spring5.Book">
        <!--set方法注入属性
            name为属性名称
            value为向属性注入的值
        -->
        <property name="bauthor" value="吴承恩"></property>
        <property name="bname" value="三国演义"></property>
    </bean>
</beans>
2.1.2.2 第二种注入方式:有参构造方法注入
<?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="order" class="com.spring.spring5.Order">
        <constructor-arg name="oname" value="火箭"></constructor-arg>
        <constructor-arg name="address" value="中国"></constructor-arg>
    </bean>
</beans>
2.1.2.3 使用p名称空间注入:可以简化基于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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--第一步:添加p名称空间在配置文件中-->
    <!--第二步:进行属性注入-->
    <bean id="book" class="com.spring.spring5.Book" p:bauthor="吴承恩" p:bname="西游记"></bean>
</beans>

2.1.3 xml注入其他类型属性

2.1.3.1 注入字面量:null与特殊字符
<?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="book" class="com.spring.spring5.Book">
        <!--set方法注入属性
            name为属性名称
            value为向属性注入的值
        -->
        <property name="bauthor" value="吴承恩"></property>
        <property name="bname">
            <value><![CDATA[<<西游记>>]]></value><!--包含特殊字符-->
        </property>
        <property name="address">
            <null></null><!--设置为null-->
        </property>
    </bean>
</beans>
2.1.3.2 注入属性-外部Bean
  1. 创建两个类service和dao类

service:

package com.spring.spring5.service;

public class UserService {
    public void add(){
        System.out.println("service add.....");
        UserDao userDao = new UserDaoImpl();
        userDao.update();
    }
}

dao:

package com.spring.spring5.dao;

public class UserDaoImpl implements UserDao{
    @Override
    public void update() {
        System.out.println("dao update.......");
    }
}

  1. 修改service,增加dao属性和set方法
package com.spring.spring5.service;

import com.spring.spring5.dao.UserDao;

public class UserService {
    //创建UserDao属性,生成set方法
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void add(){
        System.out.println("service add.....");
        userDao.update();
    }
}

  1. 编写配置文件
<?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">
    <!--service和dao对象进行创建-->
    <bean id="userDao" class="com.spring.spring5.dao.UserDaoImpl"></bean>

    <bean id="userService" class="com.spring.spring5.service.UserService">
        <!--注入userDao对象
            name:类里面的属性名称
            ref:bean对象的id
        -->
        <property name="userDao" ref="userDao">
        </property>
    </bean>
</beans>
2.1.3.3 注入属性-内部Bean
  1. 一对多关系:部门跟员工

部门类:

package com.spring.spring5.bean;

public class Dept {
    private String dname;

    public void setDname(String dname) {
        this.dname = dname;
    }
}

员工类:

package com.spring.spring5.bean;

public class Emp {
    private String ename;
    private String gender;
    //员工所属的部门,使用对象形式表示
    private Dept dept;

    public void setEname(String ename) {
        this.ename = ename;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }
}
  1. 在spring配置文件中进行相关配置
<?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的操作-->
    <bean id="emp" class="com.spring.spring5.bean.Emp">
        <property name="dept">
            <bean id="dept" class="com.spring.spring5.bean.Dept">
                <property name="dname" value="保安部"></property>
            </bean>
        </property>
        <property name="ename" value="张三"></property>
        <property name="gender" value=""></property>
    </bean>
</beans>
2.1.3.4 注入属性-级联赋值
  1. 方式一
<?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="dept" class="com.spring.spring5.bean.Dept">
        <property name="dname" value="保安部"/>
    </bean>
    <!--级联赋值-->
    <bean id="emp" class="com.spring.spring5.bean.Emp">
        <!--级联赋值-->
        <property name="dept" ref="dept"/>
        <property name="ename" value="张三"/>
        <property name="gender" value=""/>
    </bean>
</beans>
  1. 方式二
<?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="dept" class="com.spring.spring5.bean.Dept">
        <property name="dname" value="保安部"/>
    </bean>
    <!--级联赋值-->
    <bean id="emp" class="com.spring.spring5.bean.Emp">
        <property name="ename" value="张三"/>
        <property name="gender" value=""/>
        <!--级联赋值-->
        <property name="dept" ref="dept"/>
        <property name="dept.dname" value="财务部"/><!--必须有getDept()方法,否则得不到该对象-->
    </bean>
</beans>
2.1.3.5 注入属性-集合属性
  1. 创建包含数组、List、Map、Set集合的类
package com.spring.spring5.collectiontype;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Stu {
    //数组类型的属性
    private String[] courses;
    //list结合类型的属性
    private List<String> list;
    //map集合类型的属性
    private Map<String, String> maps;
    //set类型的集合
    private Set<String> sets;

    @Override
    public String toString() {
        return "Stu{" +
                "courses=" + Arrays.toString(courses) +
                ", list=" + list +
                ", maps=" + maps +
                ", sets=" + sets +
                ", courseSet=" + courseSet +
                '}';
    }

    //学生多门课程
    private Set<Course> courseSet;

    public void setCourseSet(Set<Course> courseSet) {
        this.courseSet = courseSet;
    }

    public void setSets(Set<String> sets) {
        this.sets = sets;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

    public void setCourses(String[] courses) {
        this.courses = courses;
    }

}
  1. 编写配置文件
<?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="stu" class="com.spring.spring5.collectiontype.Stu">
        <!--数组类型属性的注入-->
        <property name="courses">
            <array>
                <value>java课程</value>
                <value>数据库课程</value>
            </array>
        </property>
        <!--List集合类型属性的注入-->
        <property name="list">
            <list>
                <value>张三</value>
                <value>小三</value>
            </list>
        </property>
        <!--Map集合类型属性的注入-->
        <property name="maps">
            <map>
                <entry key="JAVA" value="java"/>
                <entry key="PHP" value="php"/>
            </map>
        </property>
        <!--Set集合类型属性的注入-->
        <property name="sets">
            <set>
                <value>MySql</value>
                <value>Redis</value>
            </set>
        </property>
        <!--注入的是Set集合类型,值是对象-->
        <property name="courseSet">
            <set>
                <ref bean="course1"/>
                <ref bean="course2"/>
            </set>
        </property>
    </bean>

    <bean id="course1" class="com.spring.spring5.collectiontype.Course">
        <property name="cname" value="spring5框架"/>
    </bean>
    <bean id="course2" class="com.spring.spring5.collectiontype.Course">
        <property name="cname" value="JDBC"/>
    </bean>
</beans>
2.1.3.6 把集合注入部分提取出来
  1. 包含list的类
package com.spring.spring5.collectiontype;

import java.util.List;

public class Book {
    private List<String> list;

    public void setList(List<String> list) {
        this.list = list;
    }

    @Override
    public String toString() {
        return "Book{" +
                "list=" + list +
                '}';
    }
}
  1. 配置文件
<?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: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>
    <!--提取list集合类型属性注入使用-->
    <bean id="book" class="com.spring.spring5.collectiontype.Book">
        <property name="list" ref="booklist"/>
    </bean>
</beans>

2.1.4 xml自动装配

根据指定装配规则(属性名称或者属性类型),Spring自动将匹配的属性值进行注入

  1. depe类
package com.xml.spring.autowire;

public class Dept {
    private int deptId;

    @Override
    public String toString() {
        return "Dept{" +
                "deptId=" + deptId +
                '}';
    }

    public int getDeptId() {
        return deptId;
    }

    public void setDeptId(int deptId) {
        this.deptId = deptId;
    }
}

  1. emp类
package com.xml.spring.autowire;

public class Emp {
    private Dept dept;

    public Dept getDept() {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "dept=" + dept +
                '}';
    }
}

  1. 将dept用自动注入的方式进行注入(spring配置文件)
<?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="dept" class="com.xml.spring.autowire.Dept">
        <property name="deptId" value="2"></property>
    </bean>

    <!--实现自动装配
        bean标签属性autowire,配置自动装配
        autowire属性有两个值:
        byName:根据属性的名称注入(注入值bean的id值和类属性名称一样)
        byType:根据属性的类型注入
    -->
    <bean id="emp" class="com.xml.spring.autowire.Emp" autowire="byType">
<!--        <property ref="dept" name="dept"></property>-->
    </bean>


</beans>

2.2 基于注解方式实现

2.2.1 什么是注解?

  • 注解是代码特殊标记,格式:@注解名称 (属性名称=属性值,属性名称=属性值)
  • 注解可以作用在类、方法、属性上面
  • 使用注解的目的是简化xml配置

2.2.2 spring针对Bean管理中创建对象提供的注解

  • @Component:任何地方都可以创建对象
  • @Service:服务层
  • @Controller:控制层
  • @Repository:DAO层

四个注解都可以用来创建对象,为了让开发更方便,习惯把每个层次用不同的注解表示

2.2.3 基于注解实现对象的创建

  1. 导入jar包
    在这里插入图片描述
  2. 开启组件扫描
<?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:component-scan base-package="com.spring.spring5.service,com.spring.spring5.dao"></context:component-scan>-->
    <!--写法二:写它的上层目录-->
    <context:component-scan base-package="com.spring.spring5"></context:component-scan>
</beans>
  1. 创建类,在类上面添加创建对象注解
package com.spring.spring5.service;

import org.springframework.stereotype.Component;

//在注解里面的value可以省略,默认就是这个类名称的第一个字母小写
@Component(value = "userService")//value相当于id,class就是当前类
public class UserService {
    public void add() {
        System.out.println("service add......");
    }
}

  1. 测试
package com.spring.spring5.service;

import org.springframework.context.support.ClassPathXmlApplicationContext;

class UserServiceTest {

    @org.junit.jupiter.api.Test
    public void add() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }
}
//service add......

2.2.4 组件扫描的细节配置

<?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">

    <!--use-default-filters="false":不使用默认的filter,自己配置filter-->
    <context:component-scan base-package="com.atguigu.springmvc" use-default-filters="false">
        <!--只扫描带Controller注解的内容-->
        <context:include-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>


    <context:component-scan base-package="com.atguigu.springmvc">
        <!--只扫描不带Controller注解的内容-->
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>

2.2.5 基于注解方式实现属性注入

2.2.5.1 常用注解
  1. @AutoWired:根据属性类型进行自动注入
  2. @Qualifier:根据属性的名称进行注入,和@AutoWired一起使用
  3. @Resource:可以根据类型注入,也可以根据名称进行注入,是java的扩展包,spring官方建议使用上面两种
  4. @Value:注入普通类型属性
2.2.5.2 代码演示
  1. dao层
package com.spring.spring5.dao;

import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao{
    @Override
    public void add() {
        System.out.println("dao add......");
    }
}
  1. service层
package com.spring.spring5.service;

import com.spring.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

//在注解里面的value可以省略,默认就是这个类名称的第一个字母小写
@Service(value = "userService")//value相当于id,class就是当前类
public class UserService {
    //    @Autowired//根据类型自动注入
//    @Qualifier(value = "userDaoImpl")//跟Autowired一起使用,在一个接口有多个实现类的时候用名称区分开
//    private UserDao userDao;

    @Resource(name = "userDaoImpl")//默认根据类型注入,加上名字就是根据名字注入
    private UserDao userDao;

    @Value(value = "service add......")//注入普通类型属性
    private String s;

    public void add() {
        System.out.println(s);
        userDao.add();
    }
}
  1. 配置文件
<?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:component-scan base-package="com.spring.spring5.service,com.spring.spring5.dao"></context:component-scan>-->
    <!--写法二:写它的上层目录-->
    <context:component-scan base-package="com.spring.spring5"></context:component-scan>
</beans>
  1. 测试
package com.spring.spring5.service;

import org.springframework.context.support.ClassPathXmlApplicationContext;

class UserServiceTest {

    @org.junit.jupiter.api.Test
    public void add() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }
}
/*
service add......
dao add......
*/

2.2.6 纯注解开发

  1. 创建配置类,替代xml配置文件
package com.spring.spring5.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration//作为配置类,替代xml配置文件
@ComponentScan(basePackages = {"com.spring.spring5"})//开启组件扫描
public class SpringConfig{

}
  1. 编写测试类
package com.spring.spring5.service;

import com.spring.spring5.config.SpringConfig;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

class UserServiceTest {

    /**
     * xml配置文件的测试方法
     */
    @Test
    public void add() {
        //加载配置文件
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }

    /**
     * 完全注解开发的测试方法
     */
    @Test
    public void test(){
        //加载配置类
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }
}

3. bean分类:普通bean与工厂bean

Spring有两种类型,一种普通的bean,另一种是工厂bean(factory bean)。

  • 普通bean:在spring的配置文件中,定义的类型就是返回的类型
  • 工厂bean:在配置文件中定义bean类型可以和返回值不一样。

3.1 代码演示

  1. 创建类,让这个类作为工厂bean,实现接口FacrotyBean,并实现方法,定义返回的类型
package com.spring.spring5.factorybean;

import com.spring.spring5.collectiontype.Course;
import org.springframework.beans.factory.FactoryBean;

public class MyBean implements FactoryBean<Course> {
    //定义返回bean
    @Override
    public Course getObject() throws Exception {
        Course course = new Course();
        course.setCname("java");
        return course;
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }
}
  1. 配置文件
<?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="myBean" class="com.spring.spring5.factorybean.MyBean"></bean>
</beans>

4. bean的作用域

  1. 在spring中,可以设置创建bean实例是单实例还是多实例
  2. 在spring中,默认设置下,bean是单实例对象(不管获取多少次,始终是那一个对象)

singleton和protorype的区别

  • singleton单实例,prototype多实例
  • 设置scope值是singleton时,加载spring配置文件时就会创建单实例对象
  • 设置scope值是prototype时,不是在加载spring配置文件的时候创建对象,是在调用getBean()时才会创建对象。
<?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="myBean" class="com.spring.spring5.factorybean.MyBean" scope="singleton"/>
    <!--多实例对象,每次获取都是不同的对象-->
    <bean id="course" class="com.spring.spring5.collectiontype.Course" scope="prototype"/>
</beans>

5. bean的生命周期

5.1 生命周期

  1. 通过构造器创建bean实例
  2. 为bean的属性设置值和对其他bean引用(调用set方法)
  3. 调用bean的初始化的方法(需要进行配置)
  4. bean可以使用了(对象获取到了)
  5. 当容器关闭的时候,会调用bean销毁的方法(需要进行配置销毁的方法)

5.2 代码演示

  1. 创建bean
package com.spring.spring5.beans;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Orders {
    private String oname;

    public Orders() {
        System.out.println("第一步:无参数构造");
    }

    public void setOname(String oname) {
        System.out.println("第二步:set方法");
        this.oname = oname;
    }

    //创建执行的初始化方法
    public void initMethod(){
        System.out.println("第三步 执行初始化的方法");
    }

    //创建执行的销毁方法
    public void destroyMethod(){
        System.out.println("第五步:执行销毁的方法");
    }

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("order.xml");
        Orders orders = context.getBean("orders", Orders.class);//第四步:得到对象
        System.out.println("第四步:得到" + orders);
        //手动销毁bean实例
        ((ClassPathXmlApplicationContext)context).close();
    }
}
/*
第一步:无参数构造
第二步:set方法
第三步 执行初始化的方法
第四步:得到com.spring.spring5.beans.Orders@10bdf5e5
第五步:执行销毁的方法
*/
  1. 编写配置文件
<?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">
    <!--init-method可以定义初始化方法
        destroy-method可以定义销毁方法
    -->
    <bean id="orders" class="com.spring.spring5.beans.Orders" init-method="initMethod" destroy-method="destroyMethod">
        <property name="oname" value="手机"/>
    </bean> 
</beans>

5.3 bean的后置处理器

5.3.1 加上bean的后置处理器bean的生命周期

  1. 通过构造器创建bean实例
  2. 为bean的属性设置值和对其他bean引用(调用set方法)
  3. 把bean的实例传递bean后置处理器的postProcessBeforeInitialization方法
  4. 调用bean的初始化的方法(需要进行配置)
  5. 把bean的实例传递bean后置处理器的postProcessAfterInitialization方法
  6. bean可以使用了(对象获取到了)
  7. 当容器关闭的时候,会调用bean销毁的方法(需要进行配置销毁的方法)

5.3.2 代码演示

  1. 创建类,实现接口BeanPsotProcessor,创建后置处理器
package com.spring.spring5.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPost implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("第三步:初始化之前执行postProcessBeforeInitialization");
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("第五步:初始化之后执行postProcessAfterInitialization");
        return null;
    }
}

  1. 创建bean
package com.spring.spring5.beans;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Orders {
    private String oname;

    public Orders() {
        System.out.println("第一步:无参数构造");
    }

    public void setOname(String oname) {
        System.out.println("第二步:set方法");
        this.oname = oname;
    }

    //创建执行的初始化方法
    public void initMethod(){
        System.out.println("第四步 执行初始化的方法");
    }

    //创建执行的销毁方法
    public void destroyMethod(){
        System.out.println("第七步:执行销毁的方法");
    }

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("order.xml");
        Orders orders = context.getBean("orders", Orders.class);//第四步:得到对象
        System.out.println("第六步:得到" + orders);
        //手动销毁bean实例
        ((ClassPathXmlApplicationContext)context).close();
    }
}

/*
 第一步:无参数构造
第二步:set方法
第三步:初始化之前执行postProcessBeforeInitialization
第四步 执行初始化的方法
第五步:初始化之后执行postProcessAfterInitialization
第六步:得到com.spring.spring5.beans.Orders@617faa95
第七步:执行销毁的方法
*/
  1. 编写配置文件
<?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">
    <!--init-method可以定义初始化方法
        destroy-method可以定义销毁方法
    -->
    <bean id="orders" class="com.spring.spring5.beans.Orders" init-method="initMethod" destroy-method="destroyMethod">
        <property name="oname" value="手机"/>
    </bean>
    <!--配置后置处理器,对此配置文件中的所有bean都有效-->
    <bean id="myBeanPost" class="com.spring.spring5.beans.MyBeanPost">
    </bean>
</beans>

6. bean引入外部属性文件

  1. 创建外部的属性文件,properties格式文件,写数据库信息(src下)
prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/userDb
prop.password=root
prop.userName=root
  1. 把外部的properties属性文件引入到spring配置文件中,并取值
<?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:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 获取properties文件内容,根据key获取,使用spring表达式获取 -->
        <property name="driverClassName" value="${prop.driverClass}"/>
        <property name="url" value="${prop.url}"/>
        <property name="username" value="${prop.userName}"/>
        <property name="password" value="${prop.password}"/>
    </bean>
</beans>
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值