Spring框架基础篇(一)

一、Spring框架
1.定义:是一个一站式的分层结构,轻量级开发框架
目前最受欢迎的框架
相当于一个对象管家,帮我们管理项目中用到的对象,就是一个容器

2.特点:
a.开元的
b.轻量级的(体积小的)
c.分成架构(按需要添加)
d.一站式(对目前流行的框架支持非常高)
3.作用:
 a.降低复杂性
 b.松耦合
 c.高性能
 d.已测试Junit
 e.声明式事物
4.搭建过程
     1.下载需要的架包
     2.导入核心包 beans context expression core  logging(日志包,不属于核心包,但是必须有,不然报错)
     3.创建编写配置文件
         创建对象,交给Spring来管理
     4.创建ApplicationContext容器
     5.通过getBean来获取到对象,如果对象不为空,则Spring搭建成功
5.核心思想

 IOC原理:inverse of control 反转控制
 1.定义:就是把对象的创建反转(交给)给Spring来管理之前,我们手动new对象,现在是为Spring拿对象
 2.实现原理:通过反射 + 配置文件 实现
 Class c = Class.forName("com.lnaou.Person");
  Object o = c.newIncetance();
  context.put("person",o);
  context.get("person");

 DI技术:dependency(依赖) injection(注入)

 依赖:类a中需要b类中提供的功能,这就是a依赖于b
 例如:service依赖dao
  UserService  
  UserDao dao = new UserDaoImplForJDBC();
   UserDao dao = new UserDaoImplForHibernate();
  使用Spring之后
  UserDao dao = context.getBean("userDaoimpl");
  //不需要改源代码就能实现组件的切换

  注入:从外部把需要的对象放到内部
  UserService
  private UserDao dao;
  set and get;
  //依赖注入,最终目的就是提高程序的扩展性,尽可能不去修改源代码
 6.bean的创建
  1.构造函数创建(默认,用这个)
  2.静态工厂创建(调用指定的静态方法获取bean)
  3.实例工厂创建(调用实例方法获取bean)
 7.依赖注入的四种方式
   1.set注入(就是通过set方法,所以必须有set方法)
   2.构造函数注入
   3.<:p的命名空间
   4.SpEL
 8.ApplicationContext 的两个实列类
  ClassPathXMLApplicationContext 用于加载class路径下的配置文件
  FileSystemXMLApplicationContext 加载系统路径下的配置文件
 9.梁总容器
  XMLBeanFactory 获取bean时才创建(不用)
  Application 加载配置时就创建
 10.bean元素属性
  scope
   singleton      单例
   prototype      多例
   request        与request生命周期一致
   session        与session生命周期一致
   init-method    对象创建完了立即执行
   destroy-method 对象销毁前执行
   id             和name作用相同
 11.复杂类型的注入
    array  使用array子标签
         例如:<array>
         <value>123</value>,<value>456></value>
         </array>


    list 使用list子标签 同array
       例如:<list>
         <value>123</value>,<value>456></value>
         </array>

   map 使用entry子标签
    例如 <map>
     <entry key ="XX" value=""></entry>
     <entry key-ref="引用数据" value=""></entry>
     </map>

     properties使用props子标签
     例如: 
     <props>
       <prop key="xx">value</prop>
     </props>
12.配置文件的模块化
  当一个配置文件内容太多时,可以将其按照功能模块划分
  1.在创建容器时,传入多个字符串对象(配置文件名)
  2.在配置文件中,使用import标签导入

13.Spring作为框架,当然不应该每次请求都创建一个新的
  希望Spring能够跟随项目的一并启动,跟随项目的停止一并销毁
      实现步骤:
      1.在web.xml中配置监听器,使得项目启动时Spring也能够一起启动
      类名org.springframework.web.context/ContextLoaderListener
      当监听到应用启动时,会创建Spring容器并且放到ApplicationContext域中
      2.WebApplicationContextUtils工具用来从WEBApplication中取出Spring容器
二.代码
Spring配置文件
applicationContext.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"
    xmlns:p="http://www.springframework.org/schema/p"

    >


 <bean name="personF" class="com.lanou.PersonFactory" >

   </bean>

   <!-- 使用静态工厂方法创建对象时,得知道静态方法在哪个类中 -->
   <bean class="com.lanou.Person" name="person">
      <!--1.set注入 属性必须提供set方法 
        value属性用于,注入基础数据类型
        ref属性用于,注入引用数据类型

      -->
      <property name="name" value="张三"></property>
      <property name="age" value="20"></property>   
      <property name="car" ref="car"></property>  
   </bean>

   <!--
    通过静态工厂方法创建
   到PersonFactory中调用getPerson的静态方法来获取对象,并放入容器中
      如果使用默认的创建方式,Spring会到对应的类中找到空参构造函数
      如果指定了factory-method Spring就到类中找到指定的静态方法执行
      class指定类型,可以与bean的类型不一致
     -->
   <bean name="person2" class="com.lanou.PersonFactory" factory-method="getPerson">
      <property name="name" value="王五"></property>
   </bean>


   <!--通过实例工厂方法创建
   到PersonFactory的某个对象中找getPerson2的方法,获取返回对象,放入容器中


     -->
    <bean name="person3" class="com.lanou.PersonFactory" factory-method="getPerson2" factory-bean="personF">
      <property name="name" value="李六"></property>
   </bean>


    <!--让Spring帮我们管理Person类的对象,这个对象的名字叫person
   class:全类名,要被管理的类的名字
   name:要被管理对象的名称
    -->
    <bean class="com.lanou.Car" name="car">
         <property name="name" value="奥迪"></property>
          <property name="color" value="黑色"></property>
    </bean>

    <!-- _____________________________________________________ -->
    <!--2.构造函数注入 调用指定的构造函数并传入参数是吸纳注入  -->
    <bean name="person4" class="com.lanou.Person">
    <!-- name指定参数名,需要与构造函数一致 位置可换
      index 指定参数放到哪一个位置,当多个构造函数参数类相同,但是顺序不同时
      type 指定参数类型,当多了构造函数的参数顺序相同,但是数据类型不同时

    -->
     <constructor-arg name="car" ref="car" index="0"></constructor-arg>
        <constructor-arg name="name" value="10086" type="int"></constructor-arg>
        <constructor-arg name="age" value="35"></constructor-arg>
    </bean>


    <!-- _____________________________________________________ -->
    <!--p命名空间 
      需要先引入命名空间
        xmlns:p="http://www.springframework.org/schema/p"
     -->
    <bean name="person5" class="com.lanou.Person" 
     p:name="老王" p:age="50" p:car-ref="car">     
    </bean>

     <!-- _____________________________________________________ -->
     <!--SpEL的注入依赖
       SpEL  Spring 的表达式的变成语言,能够实现一些简单的逻辑
       与JSP的EL 一个性质

       -->
      <bean name="person6" class="com.lanou.Person">
      <!--找到一个叫person的对象,调用getName方法获取数据  -->
           <property name="name" value="#{person.name}"></property>
           <property name="age" value="#{person5.age}"></property>
           <property name="car" ref="car"></property>
    </bean>


</beans>
Person类
package com.lanou;

public class Person {

private String name;
   private int age;
   private Car car;


   //空参构造函数
public Person() {
    System.out.println("空参构造函数RUN");
}
//使用构造函数注入,就需要提供带参数的构造

public Person(String name, int age, Car car) {
    super();
    System.out.println("构造函数1");
    this.name = name;
    this.age = age;
    this.car = car;
}

public Person( Car car,String name, int age) {
    super();
    System.out.println("构造函数2");
    this.name = name;
    this.age = age;
    this.car = car;
}

public Person( Car car,int name, int age) {
    super();
    System.out.println("构造函数2");
    this.name = name+"";
    this.age = age;
    this.car = car;
}

public Car getCar() {
    return car;
}
public void setCar(Car car) {
    this.car = car;
}
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;
}


 @Override
public String toString() {
    return "Person [name=" + name + ", age=" + age + ", car=" + car + "]";
}
 public void init() {
        System.out.println("person初始化");
 }
 public void destroy() {
    System.out.println("person销毁方法");
 }
}
PersonFactory类
package com.lanou;

public class PersonFactory {
   //静态工厂方式创建bean(当我们自己创建对象那个时使用)
    public static Person getPerson() {
        System.out.println("静态工厂方法RUN");
        return new Person();
    }

    public  Person getPerson2() {
        System.out.println("实例工厂方法RUN");
        return new Person();
    }
}
Car类:
package com.lanou;

public class Car {

       private String name,color;

    public Car() {
        super();
        // TODO Auto-generated constructor stub
    }

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

    public String getName() {
        return name;
    }

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

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

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

}
CollectionBean类
package com.lanou;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class CollectionBean {
    //演示复杂数据类型的注入

   private Object[] array;
   private List list;
   private Map map;
   private Properties properties;

public Object[] getArray() {
    return array;
}
public void setArray(Object[] array) {
    this.array = array;
}
public List getList() {
    return list;
}
public void setList(List list) {
    this.list = list;
}
public Map getMap() {
    return map;
}
public void setMap(Map map) {
    this.map = map;
}
public Properties getProperties() {
    return properties;
}
public void setProperties(Properties properties) {
    this.properties = properties;
}
@Override
public String toString() {
    return "CollectionBean [array=" + Arrays.toString(array) + ", list=" + list + ", map=" + map + ", properties="
            + properties + "]";
}


}
HelloSpring获取对象
package com.lanou;

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

public class HelloSpring {
    public static void main(String[] args) {
        //想要从容器中,获取被管理的对象
          //第一步,创建容器 (F4关系继承图)
           ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
           //2.从容器中获取bean
           Person p = (Person)ac.getBean("person");
           System.out.println(p);  

          //获取name为person2的bean
           Person p2 = (Person)ac.getBean("person2");
           System.out.println(p2);

           //获取name为person3的bean set方法注入依赖
           Person p3 = (Person)ac.getBean("person3");
           System.out.println(p3);

           //获取name为person4的bean 构造函数注入依赖,其实也是调用了set方法,为了简化书写
           Person p4 = (Person)ac.getBean("person4");
           System.out.println(p4);

         //获取name为person4的beanm  p命名空间注入依赖
           Person p5 = (Person)ac.getBean("person5");
           System.out.println(p5);

           Person p6 = (Person)ac.getBean("person6");
           System.out.println(p6);
    }
}
HelloSpring2获取对象类
package com.lanou;

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

public class HelloSpring2 {
    public static void main(String[] args) {
        //  ApplicationContext接口有两个实现类
        //从类路径下加载配置文件
        ApplicationContext ac1 = new ClassPathXmlApplicationContext("beans.xml");
   //从系统路径下加载配置文件
        ApplicationContext ac2 = new FileSystemXmlApplicationContext("beans.xml");

          Person p1 = (Person)ac1.getBean("person");
          Person p2 = (Person)ac2.getBean("person");
          System.out.println(p1);
          System.out.println(p2);
    }
}

HelloSpring3获取对象类
package com.lanou;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class HelloSpring3 {
  /*
   * Spring提供了两种容器
   * 1.BeanFactroy(已过时)它是Spring框架最古老的接口
   *  仅定义了IOC DI基础功能的接口
   *  特点:获取bean时才会创建对应的bean 以前的硬件设备资源匮乏,
   *  
   * 2.ApplicationContext
   *  它的功能更加强大
   *  特点:一旦加载配置文件就全部创建了
   *  
   */

    public static void main(String[] args) {
//       Resource resource = new FileSystemResource("/Users/lanou/javaweb/SpringDay01/src/beans.xml");
//      //  (file)Factory
//       BeanFactory factory = new XmlBeanFactory(resource );
//       System.out.println("配置加载完成");
//       System.out.println(factory.getBean("person"));

        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
//         ac.getBean("person1");
//         ac.getBean("person1");
//         ac.getBean("person1");

//         ac.getBean("person2");
//         //一般不用,关闭容器
//         ac.close();

        //获取bean并输出
           CollectionBean c = (CollectionBean)ac.getBean("cbean");
         System.out.println(c);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值