Java日志三十三「Spring入门」

**

Spring

**

Spring 是分层的 Java SE/EE 应用 full-stack 轻量级开源框架,以 IoC(Inverse Of Control: 反转控制)和 AOP(Aspect Oriented Programming:面向切面编程)为内核,提供了展现层 Spring MVC 和持久层 Spring JDBC 以及业务层事务管理等众多的企业级应用技术。

IoC的概念和作用

耦合度,是对模块间关联程度的度量。耦合的强弱取决于模块间接口的复杂性、调用模块的方式以及通过界面传送数据的多少。模块间的耦合度是指模块之间的依赖关系,包括控制关系、调用关系、数据传递关系。模块间联系越多,其耦合性越强,同时表明其独立性越差。
我们在设计系统的时候往往要求降低耦合性。

耦合度具体是什么,我们来直观的看一下:

public static void main(String[] args) throws Exception { 
	//1.注册驱动
	DriverManager.registerDriver(new com.mysql.jdbc.Driver());
}

这里是我们早期注册驱动的时候所写的代码,这里的耦合度是非常高的,下面我们来降低这段代码的耦合度

public static void main(String[] args) throws Exception { 
	//1.注册驱动
	Class.forName("com.mysql.jdbc.Driver");
}

这样写的好处就是不再依赖驱动类,就算删除mysql的驱动jar包,依然可以编译(没有mysql驱动jar包当然不可能运行)。

控制反转(Inversion Of Control):
在我们之前写代码时,需要一个对象往往是new出来的,这样是我们主动创建的此对象。而我们之前呢学过工厂类,当我们需要时,工厂给我们提供一个需要的对象,这是被动的。而IoC就是把创建对象的权利交给框架,包含依赖注入和依赖查找。

现在我们使用spring框架(基于xml):

在pom文件中导入jar包

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.10.RELEASE</version>
        </dependency>
    </dependencies>

模拟一个表现层

public class Client {
	 public static void main(String[] args) {
        //1.获取核心容器对象
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");

        //2.根据id获取Bean对象(两种方法)
        IAccountService as=(IAccountService)ac.getBean("accountService");
        IAccountDao adao=ac.getBean("accountDao",IAccountDao.class);

        System.out.println(as);
        System.out.println(adao);
    }
}

模拟一个业务层

public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

    public void  saveAccount(){
        accountDao.saveAccount();
    }    
}

模拟一个持久层

public class AccountDaoImpl implements IAccountDao {

    public  void saveAccount(){
        System.out.println("保存了账户");
    }
}

现在我们并没有配置任何东西,我们只是想在表现层打印出得到的业务层对象和持久层对象的地址。现在我们来写xml文件。
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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--    把对象的创建交给spring来管理-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>

    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean>
    
</beans>

bean标签:用于配置让spring创建对象,并且存入ioc容器之中
id 属性:对象的唯一标识。
class 属性:指定要创建对象的全限定类名

现在我们运行程序看一下结果

com.itheima.service.impl.AccountServiceImpl@60704c
com.itheima.dao.impl.AccountDaoImpl@6b19b79

打印成功,表示我们成功获得了业务层对象和持久层对象。这就是对spring的简单使用,下面我们看一下BeanFactory和ApplicationContext的区别。

首先是BeanFactory和ApplicationContext的关系,BeanFactory才是spring容器中的顶层接口,ApplicationContext是它的子接口。

具体区别:创建对象的时间点不一样。
ApplicationContext:只要一读取配置文件,默认情况下就会创建对象。 BeanFactory:什么使用什么时候创建对象

ApplicationContext接口的实现类:
ClassPathXmlApplicationContext: 它是从类的根路径下加载配置文件 (推荐,我们上面使用的就是这个)
FileSystemXmlApplicationContext: 它是从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置。
AnnotationConfigApplicationContext:
当我们使用注解配置容器对象时,需要使用此类来创建 spring 容器。它用来读取注解。

bean标签属性:
scope:指定对象的作用范围。

singleton :默认值,单例的

prototype :多例的

request :WEB项目中,Spring创建一个Bean的对象,将对象存入到request域中

session :WEB项目中,Spring创建一个Bean的对象,将对象存入到session域中

global session :WEB项目中,应用在Portlet环境.如果没有Portlet环境那么globalSession 相当于 session

单例对象和多例对象的区别:
单例对象:scope=“singleton” 一个应用只有一个对象的实例。它的作用范围就是整个引用。
生命周期:
对象出生:当应用加载,创建容器时,对象就被创建了。
对象活着:只要容器在,对象一直活着。
对象死亡:当应用卸载,销毁容器时,对象就被销毁了。

多例对象:scope=“prototype” 每次访问对象时,都会重新创建对象实例。
生命周期:
对象出生:当使用对象时,创建新的对象实例。
对象活着:只要对象在使用中,就一直活着。
对象死亡:当对象长时间不用时,被 java 的垃圾回收器回收了。

依赖注入

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

我们先来看依赖注入的第一种方式——通过构造函数的方式:
模拟一个业务层:

/**
 * 账户的业务层实现类
 */
public class AccountServiceImpl implements IAccountService {

    //经常变化的数据,并不适用于注入的方式
    private String name;
    private Integer age;
    private Date birthday;

    public AccountServiceImpl(String name, Integer age, Date birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public void  saveAccount(){
        System.out.println("AccountServiceImpl");
        System.out.println(name+","+age+","+birthday);
    }
}

现在我们在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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
        
 <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <constructor-arg name="name" value="泰斯特"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="birthday" ref="now"></constructor-arg>
    </bean>
    
</beans>

模拟一个表现层

public class Client {

    public static void main(String[] args) {
        //1.获取核心容器对象
        ClassPathXmlApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");

        IAccountService as=(IAccountService)ac.getBean("accountService");
        as.saveAccount();
    }
}

运行结果:

AccountServiceImpl
泰斯特,18,Sun Nov 22 16:07:46 CST 2020

我们可以看到成功的注入进去了,我们来分析一下这种方法的依赖注入:

构造函数注入(一般不用)
使用的标签:
constructor-arg
标签出现的位置:bean标签的内部
标签中的属性
type 指定注入数据的数据类型,也是构造函数中某些参数的类型
index 用于指定要注入的数据给构造函数中指定索引位置的参数赋值。索引位置从0开始
name 用于指定给构造函数中指定名称的参数赋值(常用)
value 用于提供基本类型和String类型数据的值
ref 用于指定其他bean类型数据,指的是在spring的Ioc核心容器中出现过的bean对象
优势:在获取bean对象时,注入数据是必须的操作,否则无法创建成功
劣势:改变了bean对象的实例化方式,即便是用不到的数据也必须提供值

下面是一个常用的依赖注入方法——通过set方法注入:

还是模拟一个业务层

/**
 * 账户的业务层实现类
 */
public class AccountServiceImpl2 implements IAccountService {

    private String name;
    private Integer age;
    private Date birthday;

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

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

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public void  saveAccount(){
        System.out.println("AccountServiceImpl");
        System.out.println(name+","+age+","+birthday);
    }
}

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

<bean id="accountService2" class="com.itheima.service.impl.AccountServiceImpl2">
        <property name="name" value="test"></property>
        <property name="age" value="20"></property>
        <property name="birthday" ref="now"></property>
    </bean>
    
</beans>

模拟表现层

public class Client {

    public static void main(String[] args) {
        //1.获取核心容器对象
        ClassPathXmlApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");

        IAccountService as=(IAccountService)ac.getBean("accountService2");
        as.saveAccount();

    }
}

结果

AccountServiceImpl2
test,20,Sun Nov 22 16:29:26 CST 2020

可以看到成功注入,现在来分析一下这种方法(常用):
优势:创建对象时没有明确的限制,可以直接使用默认构造函数
弊端:若某个成员必须有值,则获取对象时set方法没有执行

下面看一下对于集合的注入
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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="accountService3" class="com.itheima.service.impl.AccountServiceImpl3">
        <property name="myArr">
            <array>
                <value>AAA</value>
                <value>BBB</value>
                <value>CCC</value>
                <value>DDD</value>
                <value>EEE</value>
            </array>
        </property>

        <property name="myList">
            <list>
                <value>AAA</value>
                <value>BBB</value>
                <value>CCC</value>
                <value>DDD</value>
                <value>EEE</value>
            </list>
        </property>

        <property name="mySet">
            <set>
                <value>AAA</value>
                <value>BBB</value>
                <value>CCC</value>
                <value>DDD</value>
                <value>EEE</value>
            </set>
        </property>

        <property name="myMap">
            <map>
                <entry key="1" value="A"></entry>
                <entry key="2" value="B"></entry>
                <entry key="3" value="C"></entry>
                <entry key="4" value="D"></entry>
                <entry key="5" value="E"></entry>
            </map>
        </property>
        
        <property name="myProps">
            <props>
                <prop key="I">AAA</prop>
                <prop key="II">BBB</prop>
                <prop key="III">CCC</prop>
            </props>
        </property>
    </bean>

</beans>

一样来看一下结果

[AAA, BBB, CCC, DDD, EEE]
[AAA, BBB, CCC, DDD, EEE]
[AAA, BBB, CCC, DDD, EEE]
{1=A, 2=B, 3=C, 4=D, 5=E}
{III=CCC, I=AAA, II=BBB}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值