Spring学习日志

spring(IOC之xml配置部分)



框架概述

1.Spring是一个轻量级的,开源的JavaEE应用程序框架。

2.Spring是用来解决企业应用开发的复杂性。

3.具有两个核心部分:IOCAop

ⅠIOC:控制反转,把创建对象过程交给Spring进行管理

ⅡAop:面向切面,不修改源代码进行功能增加。

4.Spring特点

Ⅰ方便解耦,简化开发

ⅡAop程序支持

Ⅲ方便继承

Ⅳ方便和其他框架进行整合

Ⅴ方便事务操作

Ⅵ降低API开发难度

IOC容器

1.IOC底层原理

在这里插入图片描述

IOC也称控制反转(Inversion of Control),把对象创建和对象之间的调用过程交给Spring进行管理,可以降低代码的耦合度。

xml解析、工厂模式、反射。

2.IOC接口(BeanFactory)

1.IOC思想基于IOC容器来完成。IOC容器底层就是对象工厂

2.Spring提供了IOC容器实现的两种方式(两种接口)

ⅠBeanFactory:IOC容器的基本实现,是Spring内部的使用接口,不提供开发人员进行使用。

*加载配置文件的时候不会创建对象,在获取对象(使用)的时候才去创建对象。

ⅡApplicationContext:BeanFactory接口的子接口,提供了更多更强大的功能,一般是由开发人员进行使用的。

*加载配置文件的时候就会把在配置文件对象进行创建。

3.ApplicationContext接口有实现类
在这里插入图片描述

FileSystemXmlApplicationContext类是对应的计算机内具体路径下的配置文件

ClassPathXmlApplicationContext类是项目文件下的配置文件名

在这里插入图片描述

3.IOC操作Bean管理

1.Bean管理概念

1.Spring创建对象

2.Spring注入属性

2.Bean管理操作
Ⅰ基于xml配置文件方式实现

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

(2)在bean标签中有许多属性,介绍一些常用属性。

id属性:唯一标识

class属性:类全路径(包类路径)

name属性:可以加特殊符号作用与id属性相同

(3)创建对象时,默认也是执行无参数构造方法。

(4)注入属性:

①set化注入

step1:

	//创建属性
    private String bname;
    private String bauthor;
    //创建set方法
    public void setBname(String bname){
        this.bname = bname;
    }
    public void setBauthor(String bauthor){
        this.bauthor = bauthor;
    }

step2:

<!--使用set方法注入属性-->
<bean id="books" class="com.bluestone.spring5.book">
<!--使用property完成属性注入-->
    <property name="bauthor" value="bluestone"/>
    <property name="bname" value="HHH"/>
</bean>

②有参构造注入

step1:

public class Order {
    public String onames;
    public  String address;
    public Order(String onames,String address){
        this.address=address;
        this.onames=onames;
    }
}

step2:

<bean id="order" class="com.bluestone.spring5.Order">
        <constructor-arg index="0" value="bluestone"/>
        <constructor-arg index="1" value="XX省XX市"/>
        <constructor-arg name="address" value=""/>
        <constructor-arg name="onames" value=""/>
    </bean>

③p名称空间注入

可以简化基于xml配置的方式

step1:添加一个p名称空间

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    </beans>

step2:进行属性注入,在bean标签内操作

<bean id="books" class="com.bluestone.spring5.book" p:bauthor="HH" p:bname="AA">
    </bean>

④xml类型的其他类型注入

1.赋值为null值

<property name="author">
            <null/>
        </property>

2.属性值包括特殊符号

<!--1.用转义符号&lt &gt分别代表小于号和大于号-->
<!--2.把特殊符号写道CDATA-->
<property name="address">
            <value><![CDATA[<<忽略检查的文本>>]]></value>
        </property>

⑤注入属性外部bean

step1:创建两个类service类和dao类

//service包内
public class UserService {
    public void add(){
        System.out.println("Service add ..........");
        //原始方式:创建UserDao对象
        //UserDao userDao = new UserDaoImpl();
        //userDao.update();
    }
}
//Dao包内
public interface UserDao {
    public void update();
}
public class UserDaoImpl implements UserDao{
    @Override
    public void update() {
        System.out.println("Sercice update ..........");

    }
}

step2:在service里面调用dao的方法

public class UserService {
    private UserDao userDao;
    public void setUserDao(UserDao userDao){
        this.userDao = userDao;
    }
    public void add(){
        System.out.println("Service add ..........");
        //原始方式:创建UserDao对象
        //UserDao userDao = new UserDaoImpl();
        //userDao.update();
        userDao.update();
    }
}

step3:在Spring的配置文件中进行配置

    <bean id="userService" class="com.bluestone.service.UserService">
    <!--注入userDao对象
        name属性值:类里面属性名称
        ref属性值:创建userDao对象的bean标签id值-->
        <property name="userDao" ref="userDaoImpl"/>
    </bean>

step4:测试

    @Test
    public void TestBean(){
        ApplicationContext context = new ClassPathXmlApplicationContext("xml/bean2.xml");
        UserService userService = context.getBean("userService",UserService.class);
        userService.add();
    }

⑥xml注入集合属性

通常来说不同的属性在配置文件中都用自身所对应的标签,可以在idea快捷输入中找到

Ⅰ注入数组类型

Ⅱ注入List类型

Ⅲ注入Map类型

Ⅳ注入Set类型

step1:创建类,定义相关的类型

	private String[] name;
    private List<String> lists;
    private Map<String,String> maps;
    private Set<String> sets;

    public void setSets(Set<String> sets) {
        this.sets = sets;
    }
    public void setName(String[] name) {
        this.name = name;
    }
    public void setLists(List<String> lists) {
        this.lists = lists;
    }
    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }
    public String[] getName() {
        return name;
    }
    public List<String> getLists() {
        return lists;
    }
    public Map<String, String> getMaps() {
        return maps;
    }
    public Set<String> getSets() {
        return sets;
    }

step2:编写配置文件

<bean id="stu" class="com.bluestone.spring5.stu">
        <property name="name">
            <array>
                <value>张三</value>
                <value>李四</value>
                <value>王五</value>
            </array>
        </property>
        <property name="lists">
            <list>
                <value>Java</value>
                <value>Spring</value>
            </list>
        </property>
        <property name="maps">
            <map>
                <entry key="JAVA" value="java"/>
                <entry key="Spring" value="spring"/>
            </map>
        </property>
        <property name="sets">
            <set>
                <value>mysql</value>
                <value>redis</value>
            </set>
        </property>
    </bean>

⑦在集合中设置对象值

与其上中填入的在变量中加入对象同理,只需要将value标签更改为ref标签并且在配置文件中声明过bean对象即可。

<property name="course">
            <list>
                <ref bean="Course1"/>
                <ref bean="Course2"/>
            </list>
        </property>
    </bean>
    <bean id="Course1" class="com.bluestone.spring5.Course">
        <property name="name" value="spring"/>
    </bean>
    <bean id="Course2" class="com.bluestone.spring5.Course">
        <property name="name" value="mybatis"/>
    </bean>

⑧提取集合注入部分

step1:再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: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/beans/spring-util.xsd">

</beans>

step2:

<util:list id="book_list">
        <value>1</value>
        <value>2</value>
    </util:list>
    <bean id="book" class="com.bluestone.spring5.book">
        <property name="bname1" ref="book_list"/>
    </bean>

⑨FactoryBean

Spring中有两种Bean,一种是人为创建的普通Bean,另一种是工厂Bean。

普通Bean:再配置文件中,定义的是什么类型返回的就是什么类型

工厂Bean:再配置文件中,定义Bean类型可以和返回类型不一样。

实现:

step1:创建类,让这个类作为工厂bean,实现接口FactoryBean

step2:实现接口里面的方法,再实现的方法中定义返回的bean类型。

public class MyBean implements FactoryBean {
    @Override
    public boolean isSingleton() {
        return FactoryBean.super.isSingleton();
    }
    //定义返回Bean
    @Override
    public Object getObject() throws Exception {
        D d = new D();
        d.setName("spring");
        return d;
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }
}
3.Bean的作用域

1.在Spring中,设置创建bean实例是单实例还是多实例

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

验证:

在这里插入图片描述

由输出结果可以看出来,即使声明了多个对象但是他们的输出地址还是相同的,他们的实例并没有发生改变,所以默认情况下bean是单实例对象。

3.如何设置单实例还是多实例

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

Ⅱscope属性值

第一个值 默认值,singleton,表示是单实例对象。

第二个值prototype,表示是多实例对象

<bean id="book" class="com.bluestone.spring5.book" scope="prototype">
        <property name="bname1" ref="book_list"/>
    </bean>

在这里插入图片描述

改后再次测试,则发现两次输出的地址值改变了,因此转化为多实例对象。

4.Bean生命周期

基本生命周期

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

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

3.调用bean的初始化方法

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

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

以下为实例:

<bean id="book" class="com.bluestone.spring5.book" init-method="initmethod" destroy-method="destroymethod">
        <property name="show" value="111"/>
    </bean>
public class book {
    //创建属性
    private String show;
    //创建set方法

    public book(){
        System.out.println("第一步,通过构造器创建bean实例");
    }
    public void setShow(String show){this.show=show;System.out.println("第二步,为bean的属性设置值");}

    public void initmethod(){System.out.println("第三步,执行初始化方法");}
    public void destroymethod(){System.out.println("第五步,执行销毁的方法");}
}

@Test
    public void testbook(){
        //ApplicationContext context = new ClassPathXmlApplicationContext("xml/bean3.xml");
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("xml/bean3.xml");
        book book1 = context.getBean("book", book.class);
        System.out.println("第四步,获取创建bean实例");
        System.out.println(book1);
        context.close();
    }

在这里插入图片描述

bean的后置处理器

添加后置处理器后生命周期变为七层

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

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

3.把bean的实例传递给bean的后置处理器的方法

4.调用bean的初始化方法

5.把bean实例传递bean后置处理器的方法

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

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

演示效果:

(1)创建类,实现接口BeanPostProcessor,创建后置处理器。

public class MyBeanPost implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}

(2)配置文件中声明

<!--此配置文件下声明的所有bean都存在这个bean后置处理器-->
    <bean id="myBeanP" class="com.bluestone.spring5.MyBeanPost"></bean>
5.Bean自动装配

注:实际一般都是用注解方式做自动装配

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

过程:

<!--实现自动装配
        bean标签属性autowire,配置自动装配
        autowire属性常用两个值,
        byName根据属性名称注入,注入值bean的id值和类属性名称一样
        byType根据属性类型注入,使用byType时相同类型的类不能定义多个,定义多个会导致错误
    -->
    <bean id="emp" class="com.bluestone.autowire.Emp" autowire="byName">
        <!--<property name="dept" ref="dept"/>-->
    </bean>

byType错误类型

<bean id="emp" class="com.bluestone.autowire.Emp" autowire="byType">
        <!--<property name="dept" ref="dept"/>-->
    </bean>
<bean id="dept" class="com.bluestone.autowire.Dept"/>
<bean id="dept1" class="com.bluestone.autowire.Dept"/>

出现重复类型时会报如下错误:

Could not autowire. There is more than one bean of ‘Dept’ type. Beans: dept1,dept. Properties: ‘dept’

6.外部属性文件
1.直接配置数据库信息

(1)配置德鲁伊连接池

(2)引入德鲁伊连接池依赖jar包

(3)直接引入

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jabd:mysql://localhost:3306/userDB"/>
        <property name="username" value="root"/>
        <property name="password" value="498959702"/>
    </bean>
2.引入外部属性文件配置数据库连接池

(1)写入配置文件

prop.driverClass=com.mysql.jdbc.Driver
prop.jabd=mysql://localhost:3306/userDB
prop.username=root
prop.password=123456

(2)在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: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">

(3)用标签引入外部文件

    <!--引入外部属性文件-->
    <context:property-placeholder location="classpath:xml/jdbc.properties"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <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>
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值