spring介绍&基于xml配置Bean

时间:2019-08-23
本文章向大家介绍spring介绍&基于xml配置Bean,主要包括spring介绍&基于xml配置Bean使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

spring介绍

  spring是一个轻量级的开源框架(轻量级-指消耗资源少,开发过程快捷方便)

  方便解耦,简化开发

    Spring就是一个大工厂,可以将所有对象创建和依赖的关系维护,交给Spring管理。 --重点了解

  AOP编程的支持

    Spring提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能。

  声明式事务的支持

    只需要通过配置就可以完成对事务的管理,而无需手动编程。

  方便程序的测试

    Spring对Junit4支持,可以通过注解方便的测试Spring程序。

  方便集成各种优秀框架

    Spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架的直接支持(如:Struts、Hibernate、MyBatis等)。

  降低JavaEE API的使用难度

    Spring对JavaEE开发中非常难用的一些API(JDBC、JavaMail、远程调用等),都提供了封装,使这些API应用难度大大降低。

spring体系

  

spring大致分为5个模块:Test、AOP、web数据访问、集成部分(Data Access/Integration)、核心容器(Core Container) 

 bean、core、context可以说是spring的三大核心组件这里详细的介绍下:

  spring-core依赖注入IoC与DI的最基本实现

  spring-beansBean工厂与bean的装配

  spring-contextspring的context上下文即IoC容器

  spring-expressionspring表达式语言

   盗一张别人总结的依赖关系图

所以当我们创建完spring项目后,pom.xml文件中自动添加了spring-context后,这样依赖的core、beans等jar包就全部导入了

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

后续补充底层的实现原理

Spring最大的特性应该就是控制反转和依赖注入了

看了不下十几个对于这两个名词的解释,这里用自己的话概括下

  控制反转:就是把创建对象的权利从自己交给外部的容器,不再由自己创建,控制权发生了改变

  依赖注入:当运行一个A类需要依赖另一个B类的对象时,不需要自己new对象,而是通过容器控制程序创建对象B并注入到A里面

  下面用xml配置的方式巩固对这两种设计的理解

基于xml配置Bean

这里先介绍下标签的基本含义

  bean-定义一个Bean实例的信息 通俗的讲就是一个对象 

    bean属性:

      id       指定生成的Bean实例名称

      name     指定生成的Bean实例名称

      scope    设定Bean实例的生成方式  默认是singleton模式 还有prototype多例模式 request、session、global session模式

      init-method  初始化时调用的方法 比如对象中含有a方法,可以配置此属性这样每次生成对象时都会调用a方法    

      destroy-method  属性实例销毁时要调用的方法   同init-method 但是需要scope设置成singleton模式

    bean子标签

      property   官方的话术是用来配置Bean实例的依赖关系(set方式注入,属性一定要有set方法),通俗讲就是配置对象属性的值

      constructor-arg   用来配置Bean实例的依赖关系(构造方式注入)

      ref      constructor-arg、property、list、set、entry等标记的子标记,指定一个Bean实例

      value     constructor-arg、property、list、set、entry等标记的子标记,指定一个常量

      list   用以封装List或数组类型属性的依赖注入  具体的元素通过refvalue子标记指定

      set       封装Set类型属性的依赖注入     具体的元素通过refvalue子标记指定

      map     封装Map类型属性的依赖注入    应为map是键值对,需要用entry子标签设置“键/值”对

了解了标签基本的含义,现在实际操作下,先新建一个spring工程、在ioc的包下创建测试类User、Car;在resources下创建Spring Bean Configuration file模板的ioctest.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">

</beans>
package ioc;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

public class Car {
    private String name;
    private double price;

    public Car() {
    }

    public Car(String name, double price) {
        super();
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

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

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car [name=" + name + ", price=" + price + "]";
    }
}

 User类,写的挺多,大部分都是set、get方法

package ioc;

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

public class User {
    private String name;
    private int age;
    private String sex;
    private Car car;
    private List<Integer> intlist;
    private List<Car> carList;
    private Set<Car> carSet;
    private Map<Integer, Car> carMap;

    //默认构造方法
    public User() {
    }
    // 有参构造方法
    public User(String name, Car car, List<Car> carList) {
        super();
        this.name = name;
        this.car = car;
        this.carList = carList;
    }
    public List<Integer> getIntlist() {
        return intlist;
    }

    public void setIntlist(List<Integer> intlist) {
        this.intlist = intlist;
    }
    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    public List<Car> getCarList() {
        return carList;
    }

    public void setCarList(List<Car> carList) {
        this.carList = carList;
    }

    public Set<Car> getCarSet() {
        return carSet;
    }

    public void setCarSet(Set<Car> carSet) {
        this.carSet = carSet;
    }

    public Map<Integer, Car> getCarMap() {
        return carMap;
    }

    public void setCarMap(Map<Integer, Car> carMap) {
        this.carMap = carMap;
    }

    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + ", sex=" + sex + ", car=" + car + ", carList=" + carList
                + ", carSet=" + carSet + ", carMap=" + carMap + "]";
    };
    public void init() {
        System.out.println("开始调用");
    }
    public void destroy() {
        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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 创建一个对象user 对象名称就是user 类名用class内容表示 要加上包名 -->
    <!-- scope设置成prototype表示每次调用都会生成一个新的对象 可以打印hashcode查看 -->
    <bean name="user" class="ioc.User" scope="prototype"
        init-method="init" destroy-method="destroy">
        <!-- 构造函数参数的配置 -->
        <constructor-arg name="name" value="张三"></constructor-arg>
        <!-- 基本类型用value 引用类型用ref表示 --> 
        <constructor-arg name="car" ref="car1"></constructor-arg>
        <constructor-arg name="carList">
            <list>
            <!-- 可以在list中直接创建一个对象,但是外部无法使用 -->
                <bean id="car2" class="ioc.Car">
                    <property name="name" value="奔驰"></property>
                    <property name="price" value="1000000"></property>
                </bean>
            </list>
        </constructor-arg>
        <property name="age" value="18"></property>

    </bean>
    <bean name="user2" class="ioc.User" init-method="init"
        destroy-method="destroy">
        <!-- 通过属性的set方法给对象赋值 -->
        <property name="age" value="28"></property>
        <property name="name" value="王老五"></property>
        <property name="carSet">
            <set>
                <ref bean="car1" />
                <ref bean="car3" />
            </set>
        </property>
        <!-- 给map类型的实例赋值 -->
        <property name="carMap">
            <map>
                <entry key="1">
                    <ref bean="car1"></ref>
                </entry>
                <entry key="2">
                    <ref bean="car1"></ref>
                </entry>

            </map>
        </property>
    </bean>

    <bean id="car1" class="ioc.Car">
        <property name="name" value="宝马"></property>
        <property name="price" value="500000"></property>
    </bean>
    <bean id="car3" class="ioc.Car">
        <property name="name" value="特斯拉"></property>
        <property name="price" value="700000"></property>
    </bean>
</beans>

重新配置xml文件后,写test类验证

package ioc;

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

public class TestMain {
    public static void main(String[] args) {
        //获取容器对象
     ApplicationContext ac=new ClassPathXmlApplicationContext("ioctest.xml");
         //通过容器获取配置的javabean
     User user=(User)ac.getBean("user");
     System.out.println(user);
     User user2=(User)ac.getBean("user2");
     System.out.println(user2);
    }

}

  

原文地址:https://www.cnblogs.com/ysmdbk/p/11398482.html