Loading

Spring Bean管理

Spring的bean管理的两个操作:

  1. Spring创建对象

  2. Spring注入属性

Spring的bean管理两种实现方式

(1)基于xml配置文件方式实现

(2)基于注解方式实现

基于xml方式实现bean管理

基于xml方式创建对象的三种方式

方式1:使用默认构造函数创建,如果类中没有默认构造函数则无法创建

<!-- 配置User对象创建,使用默认构造函数的方式 -->
<bean id="user" class="com.lalala.spring5.User"></bean>

在 spring 配置文件中,使用 bean 标签,标签里面添加对应属性,就可以实现对象创建。

bean标签作用:

  • 用于配置对象让spring来创建。
  • 默认情况下它调用的是类中的无参构造函数。如果没有无参构造函数则不能创建成功。

bean标签的属性:

  • id:给对象在容器中提供一个唯一标识。用于获取对象。

  • class:指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数。

  • scope:指定对象的作用范围。

    • singleton: 默认值,单例的。
    • prototype: 多例的。
    • request: WEB项目中,Spring创建一个Bean的对象,将对象存入到request域中。
    • session: WEB项目中,Spring创建一个Bean的对象,将对象存入到session域中。
    • global session: WEB 项目中,应用在Portlet环境.如果没有Portlet环境那么globalSession相当于session。
  • init-method:指定类中的初始化方法名称。

  • destroy-method:指定类中销毁方法名称。

方式2:使用普通工厂中的方法创建对象

xml配置:

<bean id="instanceFactory" class="com.lalala.spring5.InstanceFactory"/>
<bean id="user" factory-bean="instanceFactory" factory-method="getUser"/>

工厂:

//模拟工厂类,该类我们无法通过修改源码来提供默认构造函数
public class InstanceFactory {
    public User getUser(){
        return new User();
    }
}

方式3:使用静态工厂方法

xml配置

<!--使用工厂中的静态方法创建对象-->
<bean id="user" class="com.lalala.spring5.StaticFactory" factory-method="getUser"/>

静态工厂:

public class StaticFactory {
    public static User getUser(){
        System.out.println("static factory");
        return new User();
    }
}

基于xml方式注入属性

依赖注入(Dependency Injection,DI)就是注入属性,它是spring框架核心,是 ioc 的具体实现。就是注入属性

使用set方法注入属性

新建Book类:

package com.lalala.spring5;

public class Book {
    private String bname;
    private String bauthor;

    public void setBname(String bname) {
        this.bname = bname;
    }

    public void setBauthor(String bauthor) {
        this.bauthor = bauthor;
    }

    public void testDemo(){
        System.out.println(bname+":"+bauthor);
    }
}

bean.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">
    <!--set方法注入属性-->
    <bean id="book" class="com.lalala.spring5.Book">
        <!--使用property完成属性注入
            name:类里面属性名称
            value:向属性注入的值
        -->
        <property name="bname" value="java入门到精通"></property>
        <property name="bauthor" value="啦啦啦"></property>
    </bean>
</beans>

测试代码如下:

package com.lalala.spring5.testdemo;

import com.lalala.spring5.Book;
import com.lalala.spring5.User;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {
    @Test
    public void testBook(){
        //1.加载配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean.xml");
        //2.获取配置创建的对象
        Book book = context.getBean("book", Book.class);
        System.out.println(book);
        book.testDemo();
    }
}

使用有参数构造进行注入

新建Orders类

/**
 * 使用有参数构造注入
 */
public class Orders {
    private String oname;
    private String address;

    public Orders(String oname, String address) {
        this.oname = oname;
        this.address = address;
    }

    public void ordersTest(){
        System.out.println(oname+":"+address);
    }
}

bean.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="orders" class="com.lalala.spring5.Orders">
        <constructor-arg name="oname" value="lalala"></constructor-arg>
        <constructor-arg name="address" value="中国"></constructor-arg>
    </bean>
</beans>

测试代码如下

package com.lalala.spring5.testdemo;

import com.lalala.spring5.Book;
import com.lalala.spring5.Orders;
import com.lalala.spring5.User;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {
    @Test
    public void testOrders(){
        //1.加载配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean.xml");
        //2.获取配置创建的对象
        Orders orders = context.getBean("orders", Orders.class);
        System.out.println(orders);
        orders.ordersTest();
    }
}

p名称空间注入

使用p名称空间注入,可以简化基于xml配置方式

在配置文件中添加p名称空间:

<?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.lalala.spring5.Book" p:bname="python入门到精通" p:bauthor="略略略">
    </bean>
</beans>

注入空值和特殊符号

空值注入方式:

<!--set方法注入属性-->
<bean id="book" class="com.lalala.spring5.Book">
    <property name="bname" value="java入门到精通"></property>
    <property name="bauthor" value="啦啦啦"></property>
    <!--设置空值-->
    <property name="address">
        <null/>
    </property>
</bean>

特殊符号注入方式:

<!--set方法注入属性-->
<bean id="book" class="com.lalala.spring5.Book">
    <property name="bname" value="java入门到精通"></property>
    <property name="bauthor" value="啦啦啦"></property>
    <!--属性值包含特殊符号
            1.可以把特殊符号进行转义
            2.使用CDATA
        -->
    <property name="address">
        <value><![CDATA[<<北京>>]]></value>
    </property>
</bean>

注入外部bean

在dao和service包下新建对应的类:

image-20200622145422405

bean.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">
    <!--1. Service和Dao对象创建-->
    <bean id="userService" class="com.lalala.spring5.service.UserService">
        <!--注入userDao对象
            name属性:类里面属性名称
            ref属性:创建userDao对象bean标签id
        -->
        <property name="userDao" ref="userDaoImpl"></property>
    </bean>
    <bean id="userDaoImpl" class="com.lalala.spring5.dao.UserDaoImpl"></bean>
</beans>

注入内部bean和级联赋值

注入内部bean

新建Dept和Emp类:

//部门类
public class Dept {
    private String dname;

    public void setDname(String dname) {
        this.dname = dname;
    }
    @Override
    public String toString() {
        return "Dept{" +
                "dname='" + dname + '\'' +
                '}';
    }
}
//员工类
public class Emp {
    private String ename;
    private String gender;

    private Dept dept;

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

    public Dept getDept() {
        return dept;
    }

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

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

    public void add(){
        System.out.println(ename+":"+gender+":"+dept);
    }
}

bean.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">
    <!--内部bean-->
    <bean id="emp" class="com.lalala.spring5.bean.Emp">
        <property name="ename" value="lalala"></property>
        <property name="gender" value="男"></property>
        <!--设置对象类型属性-->
        <property name="dept">
            <bean id="dept" class="com.lalala.spring5.bean.Dept">
                <property name="dname" value="保安部"></property>
            </bean>
        </property>
    </bean>
</beans>

测试代码和输出:

image-20200622152934186

级联赋值

第一种写法:

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

    <bean id="emp" class="com.lalala.spring5.bean.Emp">
        <property name="ename" value="lalala"></property>
        <property name="gender" value="男"></property>
        <!--级联赋值-->
        <property name="dept" ref="dept"></property>
    </bean>
    <bean id="dept" class="com.lalala.spring5.bean.Dept">
        <property name="dname" value="财务部"></property>
    </bean>
</beans>

第二种写法:

在Emp类中需要生成dept的get方法

image-20200622154804646

配置文件bean.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">

    <bean id="emp" class="com.lalala.spring5.bean.Emp">
        <property name="ename" value="lalala"></property>
        <property name="gender" value="男"></property>
        <!--级联赋值-->
        <property name="dept" ref="dept"></property>
        <property name="dept.dname" value="技术部"></property>
    </bean>

    <bean id="dept" class="com.lalala.spring5.bean.Dept">
    </bean>
</beans>

测试代码和输出如下

image-20200622154955956

注入集合类型

新建Stu类,其中属性如下

package com.lalala.spring5;

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;

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

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

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

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

    public void test(){
        System.out.println(Arrays.toString(courses));
        System.out.println(list);
        System.out.println(maps);
        System.out.println(sets);
    }
}

bean.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">

    <bean id="stu" class="com.lalala.spring5.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>
                <entry key="PYTHON" value="python"></entry>
            </map>
        </property>

        <!--set类型属性注入-->
        <property name="sets">
            <set>
                <value>MySql</value>
                <value>Redis</value>
            </set>
        </property>
    </bean>
</beans>

集合注入对象值

新建Course类

package com.lalala.spring5;

public class Course {
    private String cname; //课程名称
    public void setCname(String cname) {
        this.cname = cname;
    }
    @Override
    public String toString() {
        return "Course{" +
                "cname='" + cname + '\'' +
                '}';
    }
}

Stu添加集合Course

image-20200622202927971

bean.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">

    <!--1 集合类型属性注入-->
    <bean id="stu" class="com.lalala.spring5.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>
                <entry key="PHP" value="php"></entry>
            </map>
        </property>
        <!--set类型属性注入-->
        <property name="sets">
            <set>
                <value>MySQL</value>
                <value>Redis</value>
            </set>
        </property>
        <!--注入list集合类型,值是对象-->
        <property name="courseList">
            <list>
                <ref bean="course1"></ref>
                <ref bean="course2"></ref>
            </list>
        </property>
    </bean>

    <!--创建多个course对象-->
    <bean id="course1" class="com.lalala.spring5.Course">
        <property name="cname" value="Spring5框架"></property>
    </bean>
    <bean id="course2" class="com.lalala.spring5.Course">
        <property name="cname" value="MyBatis框架"></property>
    </bean>
</beans>

提取集合注入

新建Book类:

package com.lalala.spring5;

import java.util.List;

public class Book {

    private List<String> list;

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

    public void test(){
        System.out.println(list);
    }
}

在配置文件中引入名称空间util:

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

    <!--1 提取list集合类型属性注入-->
    <util:list id="bookList">
        <value>java入门</value>
        <value>pyhton入门</value>
        <value>mysql入门</value>
    </util:list>

    <!--2 提取list集合类型属性注入使用-->
    <bean id="book" class="com.lalala.spring5.Book" scope="prototype">
        <property name="list" ref="bookList"></property>
    </bean>
</beans>

FactoryBean

1、Spring 有两种类型 bean,一种普通 bean,另外一种工厂bean(FactoryBean)。
2、普通 bean:在配置文件中定义 bean 类型就是返回类型。
3、工厂 bean:在配置文件定义 bean 类型可以和返回类型不一样。

新建MyBean类:

package com.lalala.spring5.factorybean;

import com.lalala.spring5.Course;
import org.springframework.beans.factory.FactoryBean;

//第一步 创建类,让这个类作为工厂 bean,实现接口 FactoryBean
//第二步 实现接口里面的方法,在实现的方法中定义返回的 bean 类型
public class MyBean implements FactoryBean<Course> {

    @Override
    public Course getObject() throws Exception {
        Course course = new Course();
        course.setCname("abc");
        return course;
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

配置文件如下:

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

    <bean id="myBean" class="com.lalala.spring5.factorybean.MyBean">    
    </bean>
</beans>

测试代码和输出如下

image-20200622220753429

bean的作用域

在Spring中,默认情况下,bean是单实例对象。

在spring配置文件bean标签里面有属性(scope)用于设置单实例还是多实例。

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

    <bean id="book" class="com.lalala.spring5.Book" scope="prototype">

    </bean>
</beans>

测试代码和输出如下:

image-20200622222205784

bean的生命周期

从对象创建到对象销毁的过程。

(1)通过构造器创建 bean 实例(无参数构造)

(2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法)

(3)调用 bean 的初始化的方法(需要进行配置初始化的方法)

(4)bean 可以使用了(对象获取到了)

(5)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)

新建Orders类:

package com.lalala.spring5.bean;

public class Orders {
    private String oname;
    //无参构造
    public Orders() {
        System.out.println("第一步 执行无参构造创建bean实例");
    }

    public void setOname(String oname) {
        this.oname = oname;
        System.out.println("第二步 调用set方法设置属性值");
    }

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

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

配置文件如下:

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

    <bean id="orders" class="com.lalala.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyedMethod">
        <property name="oname" value="手机"></property>
    </bean>
</beans>

测试代码和输出如下:

image-20200623012244002

bean的后置处理器

bean生命周期有七步:

(1)通过构造器创建 bean 实例(无参数构造)

(2)为bean的属性设置值和对其他bean引用(调用 set 方法)

(3)把bean实例传递bean后置处理器的方法 postProcessBeforeInitialization

(4)调用bean的初始化的方法(需要进行配置初始化的方法)

(5)把 bean 实例传递 bean 后置处理器的方法 postProcessAfterInitialization

(6)bean可以使用了(对象获取到了)

(7)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)

演示添加后置处理器效果

创建类,实现接口BeanPostProcessor,创建后置处理器:

package com.lalala.spring5.bean;

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("在初始化之前执行的方法");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("在初始化之后执行的方法");
        return bean;
    }
}

配置文件添加后置处理器:

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


    <bean id="orders" class="com.lalala.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyedMethod">
        <property name="oname" value="手机"></property>
    </bean>

    <!--配置后置处理器-->
    <bean id="myBeanPost" class="com.lalala.spring5.bean.MyBeanPost"></bean>
</beans>

测试代码和输出如下:

image-20200623013635544

自动装配

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

新建Emp和Dept类:

image-20200623015918502

配置文件如下:

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

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

    <bean id="dept" class="com.lalala.spring5.autowire.Dept"></bean>
</beans>

测试代码和输出如下:

image-20200623020145694

外部属性文件

1、直接配置数据库信息

(1)引入druid的jar包

image-20200623021147740

(2)配置druid连接池

<?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: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">
    <!--直接配置连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/userDb"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
</beans>

2、引入外部属性文件配置数据库连接池

(1)创建外部属性文件,properties格式文件,写数据库信息

名称为jdbc.properties

prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/userDb
prop.userName=root
prop.password=123456

(2)把外部properties属性文件引入到spring配置文件中

引入context名称空间

<?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:util="http://www.springframework.org/schema/util"
       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/util http://www.springframework.org/schema/util/spring-util.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">
        <property name="driverClassName" value="${prop.driverClass}"></property>
        <property name="url" value="${prop.url}"></property>
        <property name="username" value="${prop.userName}"></property>
        <property name="password" value="${prop.password}"></property>
    </bean>
</beans>

基于注解方式实现bean管理

基于注解方式创建对象

(1)@Component

(2)@Service

(3)@Controller

(4)@Repository

上面四个注解功能是一样的,都可以用来创建bean实例。

第一步 引入依赖

image-20200623132031625

第二步 开启组件扫描

<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 开启注解扫描 -->
    <context:component-scan base-package="com.lalala"></context:component-scan>
</beans>

第三步 创建类在上面添加注解

//value里面的值可以省略不写,
//默认值是类名称,首字母小写,UserService -- userService
@Component(value = "userService")
public class UserService {
    public void add(){
        System.out.println("service add...");
    }
}

测试代码和输出如下

image-20200623151657196

开启组件扫描配置细节

<!--示例 1
use-default-filters="false" 表示现在不使用默认 filter,自己配置 filter
context:include-filter ,设置扫描哪些内容
-->
<context:component-scan base-package="com.atguigu" use-default￾filters="false">
    <context:include-filter type="annotation" 							                                 expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--示例 2
下面配置扫描包所有内容
context:exclude-filter: 设置哪些内容不进行扫描
-->
<context:component-scan base-package="com.atguigu">
    <context:exclude-filter type="annotation" 
        expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

基于注解方式注入属性

(1)@Autowired:根据属性类型进行自动装配

第一步,把service和dao对象创建,在service和dao类添加创建对象注解

第二步,在service注入dao对象,在service类添加dao类型属性,在属性上面使用注解

新建UserDao接口和实现类UserDaoImpl:

UserDaoImpl实现类需要添加注解,如下图所示

image-20200623160141951

在UserService注入UserDao:

//value里面的值可以省略不写,
//默认值是类名称,首字母小写,UserService -- userService
//@Component(value = "userService")
@Service
public class UserService {
    //添加注入属性注解
    @Autowired
    private UserDao userDao;
    
    public void add(){
        System.out.println("service add...");
        userDao.add();
    }
}

测试代码和运行结果如下:

image-20200623160828882

(2)@Qualifier:根据名称进行注入

这个@Qualifier注解需要和上面@Autowired一起使用

当一个接口有多个实现类时,可以使用这个注解

在UserDaoImpl上添加@Repository(value = "userDaoImpl1")

@Repository(value = "userDaoImpl1")
public class UserDaoImpl implements UserDao {
    @Override
    public void add() {
        System.out.println("dao add... ");
    }
}

UserService中使用@Qualifier(value = "userDaoImpl1")

//value里面的值可以省略不写,
//默认值是类名称,首字母小写,UserService -- userService
//@Component(value = "userService")
@Service
public class UserService {
    //添加注入属性注解
    @Autowired //根据类型进行注入
    @Qualifier(value = "userDaoImpl1") //根据名称进行注入
    private UserDao userDao;

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

测试代码同样输出如下内容

image-20200623161920864

(3)@Resource:可以根据类型注入,可以根据名称注入

//value里面的值可以省略不写,
//默认值是类名称,首字母小写,UserService -- userService
//@Component(value = "userService")
@Service
public class UserService {
    //@Resource   //根据类型进行注入
    @Resource(name = "userDaoImpl1") //根据名称进行注入
    private UserDao userDao;

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

(4)@Value:注入普通类型属性

@Service
public class UserService {
    
    @Value(value = "abc")
    private String name;

    //添加注入属性注解
    //@Autowired //根据类型进行注入
    //@Qualifier(value = "userDaoImpl1") //根据名称进行注入
    //@Resource    //根据类型进行注入
    @Resource(name = "userDaoImpl1") //根据名称进行注入
    private UserDao userDao;

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

常用注解

@Scope

@Scope指定bean的作用范围。

  • 属性:

    value:指定范围的值。

    • 取值:singleton prototype request session globalsession

@Configuration

@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。一般用于注册非表现层、业务层、持久层的对象。

示例代码:
/**
* spring 的配置类,相当于 bean.xml 文件
*/
@Configuration
@ComponentScan("com.lalala")
public class SpringConfiguration {
}

@ComponentScan

用于指定 spring 在初始化容器时要扫描的包, 作用和在 spring 的 xml 配置文件指定是一样的。

<context:component-scan base-package="com.lalala"/>

@Bean

@Bean用于把当前方法的返回值(对象)作为Bean对象存入Spring的IoC容器中。该注解只能写在方法上。

  • 属性:

    name:给当前@Bean注解的方法创建的对象指定一个名称(即bean的id)。当不写时,默认值是当前方法的名称。

/**
* 连接数据库的配置类
*/
public class JdbcConfig {
    /**
    * 创建一个数据源,并存入 spring 容器中
    * @return
    */
    @Bean(name="dataSource")
    public DataSource createDataSource() {
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setUser("root");
            ds.setPassword("1234");
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql:///spring_day02");
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

@PropertySource

@PropertySource用于加载 .properties文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到properties配置文件中,就可以使用此注解指定 properties 配置文件的位置。

@Configuration
@ComponentScan(basePackages = "com.itlalala")
@PropertySource("classpath:jdbc.properties")
public class SpringConfiguration {
}

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_test
jdbc.username=root
jdbc.password=1234

使用@Value就可以获取配置的值

@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;

完全注解开发

(1)创建配置类,替代xml配置文件

package com.lalala.spring5.config;

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

@Configuration //作为配置类,替代xml配置文件
@ComponentScan(basePackages = "com.lalala")
public class SpringConfig {

}

(2)编写测试类


public class testSpringDemo {
    @Test
    public void test2(){
        //加载配置类
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = context.getBean("userService", UserService.class);
        System.out.println(userService);
        userService.add();
    }
}

测试代码和输出:

image-20200623170947859

posted @ 2021-08-29 14:04  charlatte  阅读(281)  评论(0编辑  收藏  举报