Spring框架核心之IOC详解

IoC

Spring概述

Spring是分层的 Java SE/EE应用 full-stack(全栈式) 轻量级开源框架。
提供了表现层 SpringMVC和持久层 Spring JDBC Template以及 业务层 事务管理等众多的企业级应用技术,还能整合开源世界众多著名的第三方框架和类库,逐渐成为使用最多的Java EE 企业应用开源框
架。
两大核心:以 IOC(Inverse Of Control:控制反转)和 AOP(Aspect Oriented Programming:面向切面编程)为内核。

Spring优势

1)方便解耦,简化开发
Spring就是一个容器,可以将所有对象创建和关系维护交给Spring管理
什么是耦合度?对象之间的关系,通常说当一个模块(对象)更改时也需要更改其他模块(对象),这就是
耦合,耦合度过高会使代码的维护成本增加。要尽量解耦
2)AOP编程的支持
Spring提供面向切面编程,方便实现程序进行权限拦截,运行监控等功能。
3)声明式事务的支持
通过配置完成事务的管理,无需手动编程
4)方便测试,降低JavaEE API的使用
Spring对Junit4支持,可以使用注解测试
5)方便集成各种优秀框架
不排除各种优秀的开源框架,内部提供了对各种优秀框架的直接支持

初识IOC

控制反转(Inverse Of Control)不是什么技术,而是一种设计思想。它的目的是指导我们设计出更加松耦合的程序。
控制:在java中指的是对象的控制权限(创建、销毁)
反转:指的是对象控制权由原来 由开发者在类中手动控制 反转到 由Spring容器控制

自定义IOC容器

<dependencies>
    <dependency>
        <groupId>dom4jgroupId>
        <artifactId>dom4jartifactId>
        <version>1.6.1version>
    dependency>
    <dependency>
        <groupId>jaxengroupId>
        <artifactId>jaxenartifactId>
        <version>1.1.6version>
    dependency>
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
    dependency>
dependencies>
public interface UserDao {
     

    public void save();

}
public class UserDaoImpl implements UserDao {
     
    public void save() {
     
        System.out.println("UserDaoImpl.save。。。。。。");
    }
}
public interface UserService {
     
    public void save() throws ClassNotFoundException, IllegalAccessException, InstantiationException;
}
public class UserServiceImpl implements UserService {
     
    public void save() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
     
        UserDao userDao = (UserDao)BeanFactory.getBean("userDao");
        userDao.save();
    }
}
<beans>
    <bean id="userDao" class="com.szx.dao.impl.UserDaoImpl">bean>
beans>
public class BeanFactory {
     

    private static Map<String,Object> iocmap = new HashMap<>();
    
    //程序启动初始化对象实例
    static {
     
        //读取配置文件
        InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
        //解析xml
        SAXReader saxReader = new SAXReader();
        try {
     
            Document document = saxReader.read(resourceAsStream);
            //编写xpath表达式
            String xpath = "//bean";
            //获取所有bean标签
            List<Element> list = document.selectNodes(xpath);
            //遍历并使用反射创建对象实例存储到map集合(充当ioc容器)中
            list.forEach(item -> {
     
                String id = item.attributeValue("id");
                String className = item.attributeValue("class");
                //使用反射生成实例对象
                try {
     
                    Object o = Class.forName(className).newInstance();
                    //存储到map中
                    iocmap.put(id,o);
                } catch (InstantiationException e) {
     
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
     
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
     
                    e.printStackTrace();
                }
            });
        } catch (DocumentException e) {
     
            e.printStackTrace();
        }

    }

    //根据相应Bean,返回对应的数据
    public static Object getBean(String beanId){
     
        Object o = iocmap.get(beanId);
        return o;
    }
}
public class SpringTest {
     
    private UserService userService = new UserServiceImpl();
    @Test
    public void test1() throws IllegalAccessException, InstantiationException, ClassNotFoundException {
     
        userService.save();
    }
}

Spring入门

public interface UserDao {
     
    public void save();
}
public class UserDaoImpl implements UserDao {
     
    public void save() {
     
        System.out.println("UserDaoImpl.save。。。。。");
    }
}

<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="userDao" class="com.szx.dao.impl.UserDaoImpl">bean>

beans>
public class SpringTest {
     
    @Test
    public void test1(){
     
                //获取spring上下文对象,借助上下文对象可以获取IOC容器中的Bean对象,加载的同时放如容器中
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取Bean对象
        UserDao userDao = (UserDao)applicationContext.getBean("userDao");
        userDao.save();
    }
}

BeanFactory

BeanFactory是 IOC 容器的核心接口,它定义了IOC的基本功能。
特点:在第一次调用getBean()方法时,创建指定对象的实例

        @Test
    public void test2(){
     
        //核心接口,不会创建bean对象存到容器中
        BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
        //getBean的时候才真正创建Bean对象
        UserDao userDao = (UserDao)beanFactory.getBean("userDao");
        userDao.save();
    }

ApplicationContext

代表应用上下文对象,可以获得spring中IOC容器的Bean对象。
特点:在spring容器启动时,加载并创建所有对象的实例

1. ClassPathXmlApplicationContext
   它是从类的根路径下加载配置文件 推荐使用这种。
  
2. FileSystemXmlApplicationContext
   它是从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置。
  
3. AnnotationConfigApplicationContext
   当使用注解配置容器对象时,需要使用此类来创建 spring 容器。它用来读取注解。
    
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

常用方法

1. Object getBean(String name);
根据Bean的id从容器中获得Bean实例,返回是Object,需要强转。
2. <T> T getBean(Class<T> requiredType);
根据类型从容器中匹配Bean实例,当容器中相同类型的Bean有多个时,则此方法会报错。
3. <T> T getBean(String name,Class<T> requiredType);
根据Bean的id和类型获得Bean实例,解决容器中相同类型Bean有多个情况。

Spring配置文件

Bean标签基本配置

<bean id="" class="">bean>
* 用于配置对象交由Spring来创建。
* 基本属性:
id:Bean实例在Spring容器中的唯一标识
class:Bean的全限定名
* 默认情况下它调用的是类中的 无参构造函数,如果没有无参构造函数则不能创建成功。

Bean标签范围配置

scope属性指对象的作用范围:

singleton 默认值,单例的
prototype 多例的
request WEB项目中,Spring创建一个Bean的对象,将对象存入到request域中
session WEB项目中,Spring创建一个Bean的对象,将对象存入到session域中
global session WEB项目中,应用在Portlet环境,如果没有Portlet环境那么globalSession 相当于 session

1. 当scope的取值为singleton时
   Bean的实例化个数:1个
   Bean的实例化时机:当Spring核心文件被加载时,实例化配置的Bean实例
   Bean的生命周期:
    对象创建:当应用加载,创建容器时,对象就被创建了
    对象运行:只要容器在,对象一直活着
    对象销毁:当应用卸载,销毁容器时,对象就被销毁了
2. 当scope的取值为prototype时
   Bean的实例化个数:多个
   Bean的实例化时机:当调用getBean()方法时实例化Bean
   Bean的生命周期:
    对象创建:当使用对象时,创建新的对象实例
    对象运行:只要对象在使用中,就一直活着
    对象销毁:当对象长时间不用时,被 Java 的垃圾回收器回收了

Bean生命周期配置

<bean id="" class="" scope="" init-method="" destroy-method=""></bean>
* init-method:指定类中的初始化方法名称
* destroy-method:指定类中销毁方法名称
public class UserDaoImpl implements UserDao {
     

    public void init(){
     
        System.out.println("UserDaoImpl.init.初始化。。。。");
    }

    public void destory(){
     
        System.out.println("UserDaoImpl.destory.销毁。。。。");
    }

    public void save() {
     
        System.out.println("UserDaoImpl.save。。。。。");
    }
}
<bean id="userDao" class="com.szx.dao.impl.UserDaoImpl" init-method="init" destroy-method="destory">bean>
	//初始化及销毁
    @Test
    public void test5(){
     
        //获取spring上下文对象,借助上下文对象可以获取IOC容器中的Bean对象,加载的同时放如容器中
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取Bean对象
        UserDao userDao = (UserDao)applicationContext.getBean("userDao");
        userDao.save();
        applicationContext.close();
    }

Bean实例化三种方式

无参构造方法实例化
工厂静态方法实例化
工厂普通方法实例化

无参构造方法实例化

它会根据默认无参构造方法来创建类对象,如果bean中没有默认无参构造函数,将会创建失败

<bean id="userDao" class="com.szx.dao.impl.UserDaoImpl">bean>

工厂静态方法实例化

依赖的jar包中有个A类,A类中有个静态方法m1,m1方法的返回值是一个B对象。如果我们频繁使用B对象,此时我们可以将B对象的创建权交给spring的IOC容器,以后我们在使用B对象时,无需调用A类中的m1方法,直接从IOC容器获得。

public class StsticFactoryBean {
     
    public static UserDao createUserDao(){
     
        return new UserDaoImpl();
    }
}
<bean id="userDao" class="com.szx.factory.StsticFactoryBean" factory-method="createUserDao">bean>
@Test
public void test5(){
     
    //获取spring上下文对象,借助上下文对象可以获取IOC容器中的Bean对象,加载的同时放如容器中
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    //获取Bean对象
    UserDao userDao = (UserDao)applicationContext.getBean("userDao");
    userDao.save();
    applicationContext.close();
}

工厂普通方法实例化

依赖的jar包中有个A类,A类中有个普通方法m1,m1方法的返回值是一个B对象。如果我们频繁使用B对象,
此时我们可以将B对象的创建权交给spring的IOC容器,以后我们在使用B对象时,无需调用A类中的m1方法,直接从IOC容器获得。

public class DynamicFactoryBean {
     
    public UserDao createUserDao(){
     
        return new UserDaoImpl();
    }
}
<bean id="dynamicFactoryBean" class="com.szx.factory.DynamicFactoryBean">bean>
<bean id="userDao" factory-bean="dynamicFactoryBean" factory-method="createUserDao">bean>
@Test
public void test5(){
     
    //获取spring上下文对象,借助上下文对象可以获取IOC容器中的Bean对象,加载的同时放如容器中
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    //获取Bean对象
    UserDao userDao = (UserDao)applicationContext.getBean("userDao");
    userDao.save();
    applicationContext.close();
}

Bean依赖注入概述

依赖注入 DI(Dependency Injection):它是 Spring 框架核心 IOC 的具体实现。
在编写程序时,通过控制反转,把对象的创建交给了 Spring,但是代码中不可能出现没有依赖的情况。IOC 解耦只是降低他们的依赖关系,但不会消除。例如:业务层仍会调用持久层的方法。
那这种业务层和持久层的依赖关系,在使用 Spring 之后,就让 Spring 来维护了。简单的说,就是通过框架把持久层对象传入业务层,而不用我们自己去获取。

Bean依赖注入方式

构造方法

在UserServiceImpl中创建有参构造

public class UserServiceImpl implements UserService {
     
    private UserDao userDao;
    public UserServiceImpl(UserDao userDao){
     
        this.userDao = userDao;
    }
    @Override
    public void save() {
     
        userDao.save();
    }
}
    <bean id="userDao" class="com.szx.dao.impl.UserDaoImpl">bean>
    <bean id="userService" class="com.szx.service.impl.UserServiceImpl">

        <constructor-arg name="userDao" ref="userDao">constructor-arg>
    bean>
@Test
public void test6(){
     
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = (UserService)applicationContext.getBean("userService");
    userService.save();
}

set方法

public class UserServiceImpl implements UserService {
     
    private UserDao userDao;

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

    @Override
    public void save() {
     
        userDao.save();
    }
}
<bean id="userDao" class="com.szx.dao.impl.UserDaoImpl">bean>
<bean id="userService" class="com.szx.service.impl.UserServiceImpl">
    <property name="userDao" ref="userDao">property>
bean>
@Test
public void test6(){
     
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = (UserService)applicationContext.getBean("userService");
    userService.save();
}

P命名空间注入

P命名空间注入本质也是set方法注入,但比起上述的set方法注入更加方便,主要体现在配置文件中

public class UserServiceImpl implements UserService {
     
    private UserDao userDao;

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

    @Override
    public void save() {
     
        userDao.save();
    }
}

<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="userDao" class="com.szx.dao.impl.UserDaoImpl">bean>
    <bean id="userService" class="com.szx.service.impl.UserServiceImpl" p:userDao-ref="userDao">
    bean>

beans>
@Test
public void test6(){
     
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = (UserService)applicationContext.getBean("userService");
    userService.save();
}

Bean依赖注入的数据类型

注入数据的三种数据类型

  1. 普通数据类型
  2. 引用数据类型
  3. 集合数据类型

注入普通数据类型

public class UserDaoImpl implements UserDao {
     

    private String userName;

    private Integer age;

    public void setUserName(String userName) {
     
        this.userName = userName;
    }

    public void setAge(Integer age) {
     
        this.age = age;
    }

    public void save() {
     
        System.out.println("UserDaoImpl.save。。。。。");
        System.out.println("userName:" + userName);
        System.out.println("age:" + age);
    }
}
<bean id="userDao" class="com.szx.dao.impl.UserDaoImpl">
    
    <property name="userName" value="111">property>
    <property name="age" value="18">property>
bean>
<bean id="userService" class="com.szx.service.impl.UserServiceImpl" p:userDao-ref="userDao">
bean>
@Test
public void test6(){
     
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = (UserService)applicationContext.getBean("userService");
    userService.save();
}

注入集合数据类型

List集合注入
public class User {
     
    private String userName;
    private Integer age;

    public void setUserName(String userName) {
     
        this.userName = userName;
    }

    public void setAge(Integer age) {
     
        this.age = age;
    }

    @Override
    public String toString() {
     
        return "User{" +
                "userName='" + userName + '\'' +
                ", age=" + age +
                '}';
    }
}
public class UserDaoImpl implements UserDao {
     

    private List<Object> objectList;

    public void setObjectList(List<Object> objectList) {
     
        this.objectList = objectList;
    }

    public void save() {
     
        System.out.println("UserDaoImpl.save。。。。。");
        System.out.println(objectList);
    }
}
<bean id="user" class="com.szx.pojo.User">
    <property name="userName" value="11111">property>
    <property name="age" value="18">property>
bean>
<bean id="userDao" class="com.szx.dao.impl.UserDaoImpl">
    
    <property name="objectList">
        <list>
            <value>1111value>
            <ref bean="user">ref>
        list>
    property>
bean>
<bean id="userService" class="com.szx.service.impl.UserServiceImpl" p:userDao-ref="userDao">
bean>
Set集合注入
public class UserDaoImpl implements UserDao {
     

    private List<Object> objectList;

    private Set<Object> objectSet;

    public void setObjectSet(Set<Object> objectSet) {
     
        this.objectSet = objectSet;
    }

    public void setObjectList(List<Object> objectList) {
     
        this.objectList = objectList;
    }

    public void save() {
     
        System.out.println("UserDaoImpl.save。。。。。");
        System.out.println(objectList);
        System.out.println(objectSet);
    }
}
<bean id="user" class="com.szx.pojo.User">
    <property name="userName" value="11111">property>
    <property name="age" value="18">property>
bean>
<bean id="userDao" class="com.szx.dao.impl.UserDaoImpl">
    
    <property name="objectList">
        <list>
            <value>1111value>
            <ref bean="user">ref>
        list>
    property>
    <property name="objectSet">
        <set>
            <value>22222value>
            <ref bean="user">ref>
        set>
    property>
bean>
<bean id="userService" class="com.szx.service.impl.UserServiceImpl" p:userDao-ref="userDao">
bean>
@Test
public void test6(){
     
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = (UserService)applicationContext.getBean("userService");
    userService.save();
}
Array数组注入
public class UserDaoImpl implements UserDao {
     

    private List<Object> objectList;

    private Set<Object> objectSet;

    private Object[] objects;

    public void setObjects(Object[] objects) {
     
        this.objects = objects;
    }

    public void setObjectSet(Set<Object> objectSet) {
     
        this.objectSet = objectSet;
    }

    public void setObjectList(List<Object> objectList) {
     
        this.objectList = objectList;
    }

    public void save() {
     
        System.out.println("UserDaoImpl.save。。。。。");
        System.out.println(objectList);
        System.out.println(objectSet);
        System.out.println(Arrays.toString(objects));
    }
}
<bean id="user" class="com.szx.pojo.User">
    <property name="userName" value="11111">property>
    <property name="age" value="18">property>
bean>
<bean id="userDao" class="com.szx.dao.impl.UserDaoImpl">
    
    <property name="objectList">
        <list>
            <value>1111value>
            <ref bean="user">ref>
        list>
    property>
    <property name="objectSet">
        <set>
            <value>22222value>
            <ref bean="user">ref>
        set>
    property>
    <property name="objects">
        <array>
            <value>33333value>
            <ref bean="user">ref>
        array>
    property>
bean>
<bean id="userService" class="com.szx.service.impl.UserServiceImpl" p:userDao-ref="userDao">
bean>
@Test
public void test6(){
     
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = (UserService)applicationContext.getBean("userService");
    userService.save();
}
Map集合注入
public class UserDaoImpl implements UserDao {
     

    private List<Object> objectList;

    private Set<Object> objectSet;

    private Object[] objects;

    private Map<String,Object> objectMap;

    public void setObjectMap(Map<String, Object> objectMap) {
     
        this.objectMap = objectMap;
    }

    public void setObjects(Object[] objects) {
     
        this.objects = objects;
    }

    public void setObjectSet(Set<Object> objectSet) {
     
        this.objectSet = objectSet;
    }

    public void setObjectList(List<Object> objectList) {
     
        this.objectList = objectList;
    }

    public void save() {
     
        System.out.println("UserDaoImpl.save。。。。。");
        System.out.println(objectList);
        System.out.println(objectSet);
        System.out.println(Arrays.toString(objects));
        System.out.println(objectMap);
    }
}
<bean id="user" class="com.szx.pojo.User">
    <property name="userName" value="11111">property>
    <property name="age" value="18">property>
bean>
<bean id="userDao" class="com.szx.dao.impl.UserDaoImpl">
    
    <property name="objectList">
        <list>
            <value>1111value>
            <ref bean="user">ref>
        list>
    property>
    <property name="objectSet">
        <set>
            <value>22222value>
            <ref bean="user">ref>
        set>
    property>
    <property name="objects">
        <array>
            <value>33333value>
            <ref bean="user">ref>
        array>
    property>
    <property name="objectMap">
        <map>
            <entry key="k1" value="444444">entry>
            <entry key="k2" value-ref="user">entry>
        map>
    property>
bean>
<bean id="userService" class="com.szx.service.impl.UserServiceImpl" p:userDao-ref="userDao">
bean>
@Test
public void test6(){
     
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = (UserService)applicationContext.getBean("userService");
    userService.save();
}
Properties配置注入
public class UserDaoImpl implements UserDao {
     

    private List<Object> objectList;

    private Set<Object> objectSet;

    private Object[] objects;

    private Map<String,Object> objectMap;

    private Properties properties;

    public void setProperties(Properties properties) {
     
        this.properties = properties;
    }

    public void setObjectMap(Map<String, Object> objectMap) {
     
        this.objectMap = objectMap;
    }

    public void setObjects(Object[] objects) {
     
        this.objects = objects;
    }

    public void setObjectSet(Set<Object> objectSet) {
     
        this.objectSet = objectSet;
    }

    public void setObjectList(List<Object> objectList) {
     
        this.objectList = objectList;
    }

    public void save() {
     
        System.out.println("UserDaoImpl.save。。。。。");
        System.out.println(objectList);
        System.out.println(objectSet);
        System.out.println(Arrays.toString(objects));
        System.out.println(objectMap);
        System.out.println(properties);
    }
}
<bean id="user" class="com.szx.pojo.User">
    <property name="userName" value="11111"></property>
    <property name="age" value="18"></property>
</bean>
<bean id="userDao" class="com.szx.dao.impl.UserDaoImpl">
    <!--ref用于引用数据类型,value对应普通数据类型-->
    <property name="objectList">
        <list>
            <value>1111</value>
            <ref bean="user"></ref>
        </list>
    </property>
    <property name="objectSet">
        <set>
            <value>22222</value>
            <ref bean="user"></ref>
        </set>
    </property>
    <property name="objects">
        <array>
            <value>33333</value>
            <ref bean="user"></ref>
        </array>
    </property>
    <property name="objectMap">
        <map>
            <entry key="k1" value="444444"></entry>
            <entry key="k2" value-ref="user"></entry>
        </map>
    </property>
    <property name="properties">
        <props>
            <prop key="5555">555555</prop>
            <prop key="6666">666666</prop>
            <prop key="7777">777777</prop>
        </props>
    </property>
</bean>
<bean id="userService" class="com.szx.service.impl.UserServiceImpl" p:userDao-ref="userDao">
</bean>
@Test
public void test6(){
     
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = (UserService)applicationContext.getBean("userService");
    userService.save();
}

配置文件模块化

实际开发中,Spring的配置内容非常多,这就导致Spring配置很繁杂且体积很大,所以,可以将部分配置拆解到其他配置文件中,也就是所谓的配置文件模块化。

并列的多个配置文件

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml","applicationContext-dao.xml","applicationContext-service.xml");

主从配置文件

主文件中设置
<import resource="applicationContext-dao.xml">import>
<import resource="applicationContext-service.xml">import>

注意
同一个xml中不能出现相同名称的bean,如果出现会报错
多个xml如果出现相同名称的bean,不会报错,但是后加载的会覆盖前加载的bean

总结

<bean>标签:创建对象并放到spring的IOC容器
 id属性:在容器中Bean实例的唯一标识,不允许重复
 class属性:要实例化的Bean的全限定名
 scope属性:Bean的作用范围,常用是Singleton(默认)和prototype
 
<constructor-arg>标签:属性注入
name属性:属性名称
 value属性:注入的普通属性值
 ref属性:注入的对象引用值
<property>标签:属性注入
 name属性:属性名称
 value属性:注入的普通属性值
 ref属性:注入的对象引用值
<list>
  <set>
  <array>
  <map>
  <props>
<import>标签:导入其他的Spring的分文件

DbUtils(IOC实战)

DbUtils是Apache的一款用于简化Dao代码的工具类,它底层封装了JDBC技术。

核心对象

QueryRunner queryRunner = new QueryRunner(DataSource dataSource);

核心方法

int update(); 执行增、删、改语句
T query(); 执行查询语句
ResultSetHandler<T> 这是一个接口,主要作用是将数据库返回的记录封装到实体对象

Spring的xml整合DbUtils

<dependencies>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.47version>
    dependency>
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>druidartifactId>
        <version>1.1.9version>
    dependency>
    <dependency>
        <groupId>commons-dbutilsgroupId>
        <artifactId>commons-dbutilsartifactId>
        <version>1.6version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-contextartifactId>
        <version>5.1.5.RELEASEversion>
    dependency>
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
    dependency>
dependencies>
public class Account {
     
    private Integer id;
    private String name;
    private Double money;

    public Integer getId() {
     
        return id;
    }

    public void setId(Integer id) {
     
        this.id = id;
    }

    public String getName() {
     
        return name;
    }

    public void setName(String name) {
     
        this.name = name;
    }

    public Double getMoney() {
     
        return money;
    }

    public void setMoney(Double money) {
     
        this.money = money;
    }

    @Override
    public String toString() {
     
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}
public interface AccountDao {
     
    public List<Account> findAll();
    public Account findById(Integer id);
    public void save(Account account);
    public void update(Account account);
    public void delete(Integer id);
}
public class AccountDaoImpl implements AccountDao {
     

    private QueryRunner queryRunner;

    public void setQueryRunner(QueryRunner queryRunner) {
     
        this.queryRunner = queryRunner;
    }

    public List<Account> findAll() {
     
        String sql = "select * from account";
        try {
     
            List<Account> accountList = queryRunner.query(sql, new BeanListHandler<Account>(Account.class));
            return accountList;
        } catch (SQLException e) {
     
            e.printStackTrace();
            return null;
        }
    }

    public Account findById(Integer id) {
     
        String sql = "select * from account where id = ?";
        try {
     
            Account account = queryRunner.query(sql, new BeanHandler<Account>(Account.class),id);
            return account;
        } catch (SQLException e) {
     
            e.printStackTrace();
            return null;
        }
    }

    public void save(Account account) {
     
        String sql = "insert into account(name,money) values(?,?)";
        Object[] objects = {
     account.getName(),account.getMoney()};
        try {
     
            int update = queryRunner.update(sql, objects);
            System.out.println("save:" + update);
        } catch (SQLException e) {
     
            e.printStackTrace();
        }
    }

    public void update(Account account) {
     
        String sql = "update account set name = ? , money = ? where id = ?";
        Object[] objects = {
     account.getName(),account.getMoney(),account.getId()};
        try {
     
            int update = queryRunner.update(sql, objects);
            System.out.println("update:" + update);
        } catch (SQLException e) {
     
            e.printStackTrace();
        }
    }

    public void delete(Integer id) {
     
        String sql = "delete from account where id = ?";
        try {
     
            int update = queryRunner.update(sql, id);
            System.out.println("delete:" + update);
        } catch (SQLException e) {
     
            e.printStackTrace();
        }
    }
}
public interface AccountService {
     
    public List<Account> findAll();
    public Account findById(Integer id);
    public void save(Account account);
    public void update(Account account);
    public void delete(Integer id);
}
public class AccountServiceImpl implements AccountService {
     

    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
     
        this.accountDao = accountDao;
    }

    public List<Account> findAll() {
     
        return accountDao.findAll();
    }

    public Account findById(Integer id) {
     
        return accountDao.findById(id);
    }

    public void save(Account account) {
     
        accountDao.save(account);
    }

    public void update(Account account) {
     
        accountDao.update(account);
    }

    public void delete(Integer id) {
     
        accountDao.delete(id);
    }
}
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db
jdbc.username=root
jdbc.password=123

<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:jdbc.properties">context:property-placeholder>
    
        <beans>
            <bean id="dataSourse" class="com.alibaba.druid.pool.DruidDataSource">
                <property name="driverClassName" value="${jdbc.driver}">property>
                <property name="url" value="${jdbc.url}">property>
                <property name="username" value="${jdbc.username}">property>
                <property name="password" value="${jdbc.password}">property>
            bean>
            <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
                <constructor-arg name="ds" ref="dataSourse">constructor-arg>
            bean>
            <bean id="accountDao" class="com.szx.dao.impl.AccountDaoImpl">
                <property name="queryRunner" ref="queryRunner">property>
            bean>
            <bean id="accountService" class="com.szx.service.impl.AccountServiceImpl">
                <property name="accountDao" ref="accountDao">property>
            bean>
        beans>

beans>
public class AccountTest {
     
    private ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    private AccountService accountService = applicationContext.getBean(AccountService.class);
    @Test
    public void findAll(){
     
        List<Account> accountList = accountService.findAll();
        System.out.println(accountList);
    }
    @Test
    public void findById(){
     
        Account account = accountService.findById(1);
        System.out.println(account.toString());
    }
    @Test
    public void save(){
     
        Account account = new Account();
        account.setName("11111");
        account.setMoney(111d);
        accountService.save(account);
        findAll();
    }
    @Test
    public void update(){
     
        Account account = new Account();
        account.setName("3333");
        account.setMoney(33333d);
        account.setId(3);
        accountService.update(account);
        findAll();
    }
    @Test
    public void delete(){
     
        accountService.delete(3);
        findAll();
    }
}

小结

* DataSource的创建权交由Spring容器去完成
* QueryRunner的创建权交由Spring容器去完成,使用构造方法传递DataSource
* Spring容器加载properties文件
<context:property-placeholder location="xx.properties"/>
<property name="" value="${key}"/>

Spring注解开发

Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率。

Spring常用注解

Spring常用注解主要是替代 的配置

@Component 使用在类上用于实例化Bean
@Controller 使用在web层类上用于实例化Bean
@Service 使用在service层类上用于实例化Bean
@Repository 使用在dao层类上用于实例化Bean
@Autowired 使用在字段上用于根据类型依赖注入
@Qualifier 结合@Autowired一起使用,根据名称进行依赖注入
@Resource 相当于@Autowired+@Qualifier,按照名称进行注入
@Value 注入普通属性
@Scope 标注Bean的作用范围
@PostConstruct 使用在方法上标注该方法是Bean的初始化方法
@PreDestroy 使用在方法上标注该方法是Bean的销毁方法

JDK11以后完全移除了javax扩展导致不能使用@resource注解

<dependency>
    <groupId>javax.annotationgroupId>
    <artifactId>javax.annotation-apiartifactId>
    <version>1.3.2version>
dependency>

使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法。


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

<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    
    <context:property-placeholder location="classpath:jdbc.properties">context:property-placeholder>
    
    <context:component-scan base-package="com.szx">context:component-scan>

    <beans>
        <bean id="dataSourse" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${jdbc.driver}">property>
            <property name="url" value="${jdbc.url}">property>
            <property name="username" value="${jdbc.username}">property>
            <property name="password" value="${jdbc.password}">property>
        bean>
        <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
            <constructor-arg name="ds" ref="dataSourse">constructor-arg>
        bean>
    beans>

beans>
public interface AccountDao {
     
    public List<Account> findAll();
    public Account findById(Integer id);
    public void save(Account account);
    public void update(Account account);
    public void delete(Integer id);
}
@Repository
public class AccountDaoImpl implements AccountDao {
     

    @Autowired
    private QueryRunner queryRunner;

    public List<Account> findAll() {
     
        String sql = "select * from account";
        try {
     
            List<Account> accountList = queryRunner.query(sql, new BeanListHandler<Account>(Account.class));
            return accountList;
        } catch (SQLException e) {
     
            e.printStackTrace();
            return null;
        }
    }

    public Account findById(Integer id) {
     
        String sql = "select * from account where id = ?";
        try {
     
            Account account = queryRunner.query(sql, new BeanHandler<Account>(Account.class),id);
            return account;
        } catch (SQLException e) {
     
            e.printStackTrace();
            return null;
        }
    }

    public void save(Account account) {
     
        String sql = "insert into account(name,money) values(?,?)";
        Object[] objects = {
     account.getName(),account.getMoney()};
        try {
     
            int update = queryRunner.update(sql, objects);
            System.out.println("save:" + update);
        } catch (SQLException e) {
     
            e.printStackTrace();
        }
    }

    public void update(Account account) {
     
        String sql = "update account set name = ? , money = ? where id = ?";
        Object[] objects = {
     account.getName(),account.getMoney(),account.getId()};
        try {
     
            int update = queryRunner.update(sql, objects);
            System.out.println("update:" + update);
        } catch (SQLException e) {
     
            e.printStackTrace();
        }
    }

    public void delete(Integer id) {
     
        String sql = "delete from account where id = ?";
        try {
     
            int update = queryRunner.update(sql, id);
            System.out.println("delete:" + update);
        } catch (SQLException e) {
     
            e.printStackTrace();
        }
    }
}
public interface AccountService {
     
    public List<Account> findAll();
    public Account findById(Integer id);
    public void save(Account account);
    public void update(Account account);
    public void delete(Integer id);
}
@Service
public class AccountServiceImpl implements AccountService {
     

    @Autowired
    private AccountDao accountDao;

    public List<Account> findAll() {
     
        return accountDao.findAll();
    }

    public Account findById(Integer id) {
     
        return accountDao.findById(id);
    }

    public void save(Account account) {
     
        accountDao.save(account);
    }

    public void update(Account account) {
     
        accountDao.update(account);
    }

    public void delete(Integer id) {
     
        accountDao.delete(id);
    }
}
public class AccountTest {
     
    private ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    private AccountService accountService = applicationContext.getBean(AccountService.class);
    @Test
    public void findAll(){
     
        List<Account> accountList = accountService.findAll();
        System.out.println(accountList);
    }
}

Spring新注解

@Configuration 用于指定当前类是一个Spring 配置类,当创建容器时会从该类上加载注解
@Bean 使用在方法上,标注将该方法的返回值存储到 Spring 容器中
@PropertySource 用于加载 properties 文件中的配置
@ComponentScan 用于指定 Spring 在初始化容器时要扫描的包
@Import 用于导入其他配置类

Spring纯注解

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db
jdbc.username=root
jdbc.password=123
@PropertySource("classpath:jdbc.properties")    //配置,用于获取外部配置文件
public class DataSourseConfig {
     
    @Value("${jdbc.driver}")
    private String driver;

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

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

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

    /**
     * 配置德鲁伊数据库连接池信息
     * @return
     */
    @Bean("dataSource") //不起名则为方法名
    public DataSource getDataSource(){
     
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }
}
@Configuration  //核心配置类
@ComponentScan("com.szx")   //开始扫描注解的注解,指定包下的注解都会扫描
@Import(DataSourseConfig.class)     //加载第三方类
public class SpringConfig {
     

    /**
     * 于容器中获取以注入的DataSource,并创建QueryRunner
     * @param dataSource
     * @return
     */
    @Bean("queryRunner")
    public QueryRunner getQueryRunner(@Autowired DataSource dataSource){
     
        QueryRunner queryRunner = new QueryRunner(dataSource);
        return queryRunner;
    }

}
public class AccountTest {
     

    AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
    AccountService accountService = (AccountService)annotationConfigApplicationContext.getBean("accountService");


    @Test
    public void findAll(){
     
        List<Account> accountList = accountService.findAll();
        System.out.println(accountList);
    }
}

Spring整合Junit

普通Junit测试问题

在普通的测试类中,需要开发者手动加载配置文件并创建Spring容器,然后通过Spring相关API获得Bean实例;如果不这么做,那么无法从容器中获得对象。

AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
AccountService accountService = (AccountService)annotationConfigApplicationContext.getBean("accountService");

Spring整合Junit


<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-testartifactId>
    <version>5.1.5.RELEASEversion>
dependency>
<dependency>
    <groupId>junitgroupId>
    <artifactId>junitartifactId>
    <version>4.12version>
    <scope>testscope>
dependency>
@RunWith(SpringJUnit4ClassRunner.class)     //指定junit的运行环境  SpringJUnit4ClassRunner:spring提供的作为junit运行环境的类
//@ContextConfiguration({"classpath:applicationContext.xml"})
@ContextConfiguration(classes = {
     SpringConfig.class})       //加载核心配置类
public class AccountTest {
     

    @Autowired
    private AccountService accountService;


    @Test
    public void findAll(){
     
        List<Account> accountList = accountService.findAll();
        System.out.println(accountList);
    }
}

你可能感兴趣的:(spring,java,ioc,后端)