spring使用基础(1)

这是一个改善架构的框架,一个面向架构的框架。他所追求的东西是无入侵式的设计。在开发中我们至少做到最少入侵。

spring的使用特点是你几乎不需要了解或使用到api

 

环境搭建

  spring2.5是需要一个spring.jar和一个logging.jar即可。spring3及以上版本自己百度。这里不依依叙述

 

依赖注入

对象的创建方式

 普通方式

  <bean id="beanName" class="className"></bean>

  测试代码:

     //启动spring容器
          ApplicationContext context =
                    new ClassPathXmlApplicationContext("applicationContext.xml");
          //根据id把spring容器中的bean提取出来了
          Person person = (Person)context.getBean("beanName");
          person.hello();

  这种方式非常常用。applicationContext.xml是你得配置文件

静态工厂方式

  <bean id="xxxxxx"
        class="com.staticFactory

     factory-method="getInstance"></bean>

  一个对象xxxxx的创建可以交给staticFactory完成,你只需要在你的工厂中定义好你要创建的对象,提供一个静态的方法getInstance

实力工厂方式

   <!--
        factory-bean是一个工厂bean
        factory-method是一个工厂方法
      -->    
    <bean id="InstanceFactory"
        class="com.InstanceFactory"></bean>    
    <bean id="xxx"
        factory-bean="InstanceFactory"
        factory-method="getInstance"></bean>

  实例工厂的方式不像静态那样,实例工厂必须有一个bean,然后xxx的factory-bean指定调用instanceFactory.

  factory-Method指定调用工厂的方法

 

 给id取别名

    <bean id="LoadBalanceOfDetails" class="com.itheima12.spring.alias.HelloWorld"></bean>

    <!--
          name的属性的值要和id对应
       -->
      <alias name="LoadBalanceOfDetails" alias="Details"/>
      <alias name="LoadBalanceOfDetails" alias="Details"/>

    context.getbean("Details")即可取得

对象创建的时间

  这类问题不好描述,平时我也不会去记。构造方法写好大哥断点就知道了。

  默认下启动容器的时候读取配置文件就初始化bean了。

   在bean中修改一个属性lazy-init="true",就会在使用的时候加载。记得没错的话应该是getBean的时候才加载

 

 

 

容器中的对象默认是单例的

如果修改<bean ........  scope=”prototype”>则变成多例的

以后的action service dao都需要设置这个scope.

action永远是多例  servicedao是单例的

 注意:scope为prototype的时候产生的对象就是多实例的。这时候无论lazy-init是什么值都要在getbean的时候才能创建

 

 spring的init和destroy执行流程

  1创建一个spring容器的对象

  2加载创建配置文件中的bean(这里bean不能是多实例的,lazy-init不能为true)

  3执行一个对象的init方法

  4利用getBean得到一个对象,如果这个对象是多例的或者lazy-init为true,则创建对象

  5对象调用方法

  6spring容器关闭的时候执行destroy方法

 

 

 

以上就是spring 2.0 以前具备的功能。叫做IOC--------控制反转

通俗的说法就是把对象的创建交给容器。

后来就加入了DI(依赖注入)

 

 

 

依赖注入

 

Spring容器的DI-xml-setter的方法

非常简单,直接上代码

public class Person {
    private Long pid;
    private String name;
    private Student student;
    private List lists;
    private Set sets;
    private Map map;
    private Properties properties;
    private Object[] objects;

  //get and set

public class student{

}

配置文件的写法

<bean id="person" class="com.itheima12.spring.di.xml.setter.Person">
           <!--
               property就是一个bean的属性
                 name就是用来描述属性的名称
                 value就是值,如果是一般类型(基本类型和String)
            -->
           <property name="pid" value="1"></property>
           <property name="name" value="狗蛋"></property>
           <!--
               spring容器内部创建的student对象给Person的student对象赋值了
            -->
           <property name="student">
               <ref bean="student"/>
           </property>
           
           <property name="lists">
               <list>
                   <value>list1</value>
                   <value>list2</value>
                   <ref bean="student"/>
               </list>
           </property>
           <property name="sets">
               <set>
                   <value>set1</value>
                   <value>set2</value>
                   <ref bean="student"/>
               </set>
           </property>
           <property name="map">
               <map>
                   <entry key="m1">
                       <value>map1</value>
                   </entry>
                   <entry key="m2">
                       <ref bean="student"/>
                   </entry>
               </map>
           </property>
           <property name="properties">
               <props>
                   <prop key="p1">prop1</prop>
                   <prop key="p2">prop2</prop>
               </props>
           </property>
           <property name="objects">
               <list>
                   <value>obj1</value>
                   <ref bean="student"/>
               </list>
           </property>
   </bean>
   <bean id="student" class="com.itheima12.spring.di.xml.setter.Student"></bean>

 

DI:依赖注入:给对象的属性赋值,以上我们是使用set xml的方式

给对象赋值叫做装配。有了依赖注入装配就能够整合所有的框架了。

 

SpringIOCDI的意义

这里我们来模拟一个场景。

首先我有一个文档的接口

public interface Document {
    /**
     * 读取文档
     */
    public void readDocument();
    /**
     * 写文档
     */
    public void writeDocument();
}

所有的操作文件的软件都实现这个接口,具备读和写的功能。

首先是Excel

public class ExcelDocument implements Document {
    public void readDocument() {
        // TODO Auto-generated method stub
        System.out.println("excel read");
    }
    public void writeDocument() {
        // TODO Auto-generated method stub
        System.out.println("excel write");
    }
}

其次是

WordDocument、PDFDocument。

 

然后我有一个管理员类,内部维护了一个文档

public class Manager {
    private Document document;
    public Document getDocument() {
        return document;
    }
    public void setDocument(Document document) {
        this.document = document;
    }
    public void readDocument(){
        this.document.readDocument();
    }
    public void writeDocument(){
        this.document.writeDocument();
    }
}

 

我们来看依赖注入的意义和好处。首先我们看看传统方式的写法:

@Test
    public void testDocument_NOSpring(){
        //为不完全的面向接口编程
        Document document = new WordDocument();
        Manager manager = new Manager();
        manager.setDocument(document);
        manager.readDocument();
        manager.writeDocument();
    }

这种方式有很多不好。将实现类new出来,程序缺乏灵活性。而且既然你都写死了实现类,

就好像一个USB接口固定了一个U盘。我要是想插硬盘那就需要修改机器了。真正的灵活是

我想插什么设备就什么设备,接口的提供只是定义功能,具体的功能实现不能写死。

<!--
           把documentManager,wordDocument,excelDocument,pdfDocument放入到spring容器中
    -->
   <bean id="Manager" class="com.Manager">
           <!--
               该属性是一个接口
            -->
           <property name="document">
               <ref bean="实现类"/>
           </property>
   </bean>
   <bean id="wordDocument" class="com.WordDocument"></bean>
   <bean id="excelDocument" class="com.ExcelDocument"></bean>
   <bean id="pdfDocument" class="com.PDFDocument"></bean>

 

/**
     * IOC和DI结合的真正的意义:java代码端完全的面向接口编程
     */
    @Test
    public void testDocument_Spring(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        DocumentManager documentManager = (DocumentManager)context.getBean("documentManager");
        documentManager.writeDocument();
        documentManager.readDocument();
    }

你需要什么实现就在配置文件中修改  程序不修改。

 

模拟MVC

   <bean id="personDao" class="com.PersonDaoImpl"></bean>
   <bean id="personService" class="com.PersonServiceImpl">
           <property name="personDao">
               <ref bean="personDao"/>
           </property>
   </bean>
   <bean id="personAction" class="com.PersonAction">
           <property name="personService">
               <ref bean="personService"/>
           </property>
   </bean>

 

其实spring的使用非常简单和舒服。我以前学struts,和hibernate用了很长时间,尤其是struts。看了很久的书也还是搞不明白。

归根结底是个人能力因素,但是框架的设计因素也占了很大。入侵式的设计,很多API,尤其是struts给我打击很大。为什么web专用的

servlet你不用非要用拦截器搞的那么复杂。后来索性直接去找工作。找到的第一份工作接触了spring,看看例子觉得非常清爽。后来跟着

使用了springMVC也是一个爽字,几乎不会报错,即使有也能很快解决,到最后的mybatis,都非常好用。

后面我会继续深入spring源码做一次分析。

 

通过构造器注入

public class Person {
    private Long pid;
    private String name;
    private Student student;
    private List lists;
    private Set sets;
    private Map map;
    private Properties properties;
    private Object[] objects;

 

  public Person(){}

  public Person(String name, Student student) {
        super();
        this.name = name;
        this.student = student;
    }

配置文件:

<bean id="person" class="com.Person">
           <!--
               constructor-arg指的是构造器中的参数
                index 下标  从0开始
                value 如果一般类型,用value赋值
                ref   引用类型赋值
            -->
           <constructor-arg index="0" value="asdfsafd"></constructor-arg>
           <constructor-arg index="1" ref="student"></constructor-arg>
   </bean>

context.getBean("person")就可以获得注入了值的对象。

如果你想既可以使用构造器注入又可以使用set注入那就一定要提供默认的无参构造器方法,

并且给Javabean提供所有属性的get  set

一般习惯上都喜欢提供get set 以及无参构造函数。

 

Spring容器的继承

  有两个类 PersonStudent  Student extends Person

  Personname属性

  在配置中:

    在....父类中进行赋值,子类通过parent属性继承

      <bean id=”person” class=””>

        <property name=”name” value=”aaa”></property>

      </bean>

    parent实现了spring容器内部的继承

    <bean id=”student” class=”” parent=person> </bean>

    当然因为Java的继承机制,只要父类提供get set那么子类就可以继承这些方法自然可以设置和得到属性并赋值

    <bean id=”student2” class=”” >

      <property name=”name” value=”xcvxcvxcvx”/>

    </bean>

 

 

Spring容器的注解

 

要理解注解就一定要能够自定义注解。并且使用自定义注解。这里是后面容器注解的一个前提铺垫。

 

元注解:能够注解注解的注解。就像元数据一样,能够描述数据的数据

 

  1.@Target,
 2.@Retention,
 3.@Documented,
 4.@Inherited

 

 

 

java.lang.annotation中可以查阅这些类型以及他们所支持的类

 

 

 

@Target:

 

  @Target说明了Annotation所修饰的对象范围:Annotation可被用于 packagestypes(类、接口、枚举、Annotation类型)、类型成员(方法、 构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch 参数)。在Annotation类型的声明中使用了target可更加明晰其修饰的目标。

 

  作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)

 

  取值(ElementType)有:

 

    1.CONSTRUCTOR:用于描述构造器
    2.FIELD:用于描述域
    3.LOCAL_VARIABLE:用于描述局部变量
    4.METHOD:用于描述方法
    5.PACKAGE:用于描述包
    6.PARAMETER:用于描述参数
    7.TYPE:用于描述类、接口(包括注解类型) enum声明

 

@Target(ElementType.TYPE)//声明Table只能对对类,接口,枚举进行注解

 

public @interface Table {

 

public String tableName() default "xxxx";

 

}

 

@Table(tableName="我草你妹")//如果不写tableName默认他的值就是xxxx

 

class Person{

 

private String name;

 

}

 

 

 

@Retention

 

@Retention定义了该Annotation被保留的时间长短:某些Annotation仅出现在源代码中,而被编译器丢弃;而另一些却被编译在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,而另一些在class被装载时将被读取(请注意并不影响class的执行,因为Annotation与class在使用上是被分离的)。使用这个meta-Annotation可以对 Annotation的“生命周期”限制。

 

 作用:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效)

 

  取值(RetentionPoicy)有:

 

    1.SOURCE:在源文件中有效(即源文件保留)
    2.CLASS:class文件中有效(即class保留)
    3.RUNTIME:在运行时有效(即运行时保留)

 

@Target(ElementType.FIELD)

 

@Retention(RetentionPolicy.RUNTIME)

 

public @interface Column {

 

public String name() default "fieldName";

 

    public String setFuncName() default "setField";

 

    public String getFuncName() default "getField";

 

    public boolean defaultDBValue() default false;

 

}

 

 

 

class Person{

 

@Column(name="xxx",setFuncName="sdfsdf")

 

private String name;

 

}

 

Column注解的的RetentionPolicy的属性值是RUTIME,这样注解处理器可以通过反射,获取到该注解的属性值,从而去做一些运行时的逻辑处理

 

@Documented:

 

@Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。说白了用来生成文档的

 

@Target(ElementType.FIELD)

 

@Retention(RetentionPolicy.RUNTIME)

 

@Documentedpublic @interface Column {

 

    public String name() default "fieldName";

 

    public String setFuncName() default "setField";

 

    public String getFuncName() default "getField";

 

    public boolean defaultDBValue() default false;

 

}

 

 

 

@Inherited

 

  @Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。

 

  注意:@Inherited annotation类型是被标注过的class的子类所继承。类并不从它所实现的接口继承annotation,方法并不从它所重载的方法继承annotation

 

  当@Inherited annotation类型标注的annotationRetentionRetentionPolicy.RUNTIME,则反射API增强了这种继承性。如果我们使用java.lang.reflect去查询一个@Inherited annotation类型的annotation时,反射代码检查将展开工作:检查class和其父类,直到发现指定的annotation类型被发现,或者到达类继承结构的顶层。

 

  实例代码:

 

 

 

/**

 

 *

 

 * @author peida

 

 *

 

 */

 

@Inheritedpublic @interface Greeting {

 

    public enum FontColor{ BULE,RED,GREEN};

 

    String name();

 

    FontColor fontColor() default FontColor.GREEN;

 

}

 

 

 

自定义注解:

 

  使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口,由编译程序自动完成其他细节。在定义注解时,不能继承其他的注解或接口。@interface用来声明一个注解,其中的每一个方法实际上是声明了一个配置参数。方法的名称就是参数的名称,返回值类型就是参数的类型(返回值类型只能是基本类型、ClassStringenum)。可以通过default来声明参数的默认值。

 

  定义注解格式:
  public @interface 注解名 {定义体}

 

  注解参数的可支持数据类型:

 

    1.所有基本数据类型(int,float,boolean,byte,double,char,long,short)
    2.String类型
    3.Class类型
    4.enum类型
    5.Annotation类型
    6.以上所有类型的数组

 

  Annotation类型里面的参数该怎么设定:
  第一,只能用public或默认(default)这两个访问权修饰.例如,String value();这里把方法设为defaul默认类型;   
  第二,参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和 String,Enum,Class,annotations等数据类型,以及这一些类型的数组.例如,String value();这里的参数成员就为String;  
  第三,如果只有一个参数成员,最好把参数名称设为"value",后加小括号.:下面的例子FruitName注解就只有一个参数成员。

 

 

 

按列:

 

 简单的自定义注解和使用注解实例:

 

 

 

package annotation;

 

import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;

 

/**

 

 * 水果名称注解

 

 * @author peida

 

 *

 

 */

 

@Target(ElementType.FIELD)

 

@Retention(RetentionPolicy.RUNTIME)

 

@Documentedpublic @interface FruitName {

 

    String value() default "";

 

}

 

 

 

 

 

package annotation;

 

import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;

 

/**

 

 * 水果颜色注解

 

 * @author peida

 

 *

 

 */

 

@Target(ElementType.FIELD)

 

@Retention(RetentionPolicy.RUNTIME)

 

@Documentedpublic @interface FruitColor {

 

    /**

 

     * 颜色枚举

 

     * @author peida

 

     *

 

     */

 

    public enum Color{ BULE,RED,GREEN};

 

    

 

    /**

 

     * 颜色属性

 

     * @return

 

     */

 

    Color fruitColor() default Color.GREEN;

 

 

 

}

 

 

 

 

 

package annotation;

 

import annotation.FruitColor.Color;

 

public class Apple {

 

    

 

    @FruitName("Apple")

 

    private String appleName;

 

    

 

    @FruitColor(fruitColor=Color.RED)

 

    private String appleColor;

 

    

 

    

 

    

 

    

 

    public void setAppleColor(String appleColor) {

 

        this.appleColor = appleColor;

 

    }

 

    public String getAppleColor() {

 

        return appleColor;

 

    }

 

    

 

    

 

    public void setAppleName(String appleName) {

 

        this.appleName = appleName;

 

    }

 

    public String getAppleName() {

 

        return appleName;

 

    }

 

    

 

    public void displayName(){

 

        System.out.println("水果的名字是:苹果");

 

    }

 

}

 

 

 

 

 

注解元素的默认值:

 

注解元素必须有确定的值,要么在定义注解的默认值中指定,要么在使用注解时指定,非基本类型的注解元素的值不可为null。因此, 使用空字符串或0作为默认值是一种常用的做法。这个约束使得处理器很难表现一个元素的存在或缺失的状态,因为每个注解的声明中,所有元素都存在,并且都具有相应的值,为了绕开这个约束,我们只能定义一些特殊的值,例如空字符串或者负数,一次表示某个元素不存在,在定义注解时,这已经成为一个习惯用法。例如:

 

 

 

 

 

  定义了注解,并在需要的时候给相关类,类属性加上注解信息,如果没有响应的注解信息处理流程,注解可以说是没有实用价值。如何让注解真真的发挥作用,主要就在于注解处理方法,下一步我们将学习注解信息的获取和处理!

 

 

 

按列2

 

@Target(ElementType.TYPE)

 

@Retention(RetentionPolicy.RUNTIME)

 

public @interface ClassInfo {

 

String name() default "";

 

}

 

 

 

@Target(ElementType.METHOD)

 

@Retention(RetentionPolicy.RUNTIME)

 

public @interface MethodInfo {

 

String name() default "";

 

}

 

 

 

@ClassInfo(name="类的注解")

 

public class Client {

 

@MethodInfo(name="方法的注解")

 

public void java(){

 

 

 

}

 

}

 

public class annotationParse {

 

public static void parse(){

 

Class clazz=Client.class;

 

if(clazz.isAnnotationPresent(ClassInfo.class)){

 

ClassInfo classInfo=(ClassInfo) clazz.getAnnotation(ClassInfo.class);

 

System.out.println(classInfo.name());

 

}

 

 

 

 

 

Method[] methods = clazz.getMethods();

 

for (Method method : methods) {

 

//判断该方法上面是否存在MethodInfo注解

 

if(method.isAnnotationPresent(MethodInfo.class)){

 

//获取到方法上面的注解

 

MethodInfo methodInfo = method.getAnnotation(MethodInfo.class);

 

System.out.println(methodInfo.name());

 

}

 

}

 

 

 

}

 

 

 

@Test

 

public void test(){

 

annotationParse.parse();

 

}

 

}

 

 

 

Spring容器的依赖注入

 

public class Person {

 

@Resource

 

//@Autowired按照类型匹配

 

//@Qualifier("student")按照id匹配

 

private Student student;

 

public Student getStudent() {

 

return student;

 

}

 

public void setStudent(Student student) {

 

this.student = student;

 

}

 

}

 

 

 

 

 

 

 

public class Student {

 

public void say(){

 

System.out.println("窗前明月光\r\n,疑是地上霜\r\n,举头望明月\r\n,低头思故乡");

 

}

 

}

 

使用注解注入需要将约束文件改成这里的约束

 

<?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-2.5.xsd

 

           http://www.springframework.org/schema/context

 

           http://www.springframework.org/schema/context/spring-context-2.5.xsd">

 

   <bean id="person" class="com.itheima12.spring.di.annotation.Person"></bean>

 

   <bean id="student" class="com.itheima12.spring.di.annotation.Student"></bean>

 

   <!--

 

    启动依赖注入的注解解析器

 

    -->

 

    <context:annotation-config></context:annotation-config>

 

</beans>

 

  @Resource注解的属性会拿着属性名去和配置中的ID做比较,找到匹配的就赋值,如果没找到就会拿属性名的类型去和配置文件中的类型比较,

  找到后注解

 

  如果@Resource(name="student")就只会那student作为id去和配置文件中的id匹配比较赋值

 

 原理

 

     1、当启动spring容器的时候,创建两个对象

 

   2、当spring容器解析到 <context:annotation-config></context:annotation-config>

 

    spring容器会在spring容器管理的bean的范围内查找这些类的属性上面是否加了@Resource注解

 

     3spring解析@Resource注解的name属性

 

    如果name属性为""

 

               说明该注解根本没有写name属性

 

              spring容器会得到该注解所在的属性的名称和spring容器中的id做匹配,如果匹配成功,则赋值

 

                                                                 如果匹配不成功,则按照类型进行匹配

 

            如果name属性的值不为""

 

                 则按照name属性的值和springid做匹配,如果匹配成功,则赋值,不成功,则报错

 

    说明:

 

        注解只能用于引用类型

 

        注解写法比较简单,但是效率比较低

 

       xml写法比较复杂,但是效率比较高

 

  注解写法简单效率低  xml写法复杂但是效率高(不过差别不大,企业喜欢用注解)

 

Spring容器的类扫描注入

 

类扫描器的加入可以连bean都不用写

 

<?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-2.5.xsd

 

           http://www.springframework.org/schema/context

 

           http://www.springframework.org/schema/context/spring-context-2.5.xsd">

 

   <!--

 

    component:把一个类放入到spring容器中,该类就是一个component

 

    base-package指定的包及子包下扫描所有的类

 

    -->

 

    <context:component-scan base-package="coms.can"></context:component-scan>

 

</beans>

 需要加入容器的的类

@Component("person")

 

public class Person {

 

  @Resource(name="student")

 

  private Student student;

 

  public Student getStudent() {

 

    return student;

 

  }

 

}

 

 

原理就是

1启动spring容器解析xml文件

当解析到 <context:component-scan base-package="com.scan">

   </context:component-scan>的时候就会在制定包下扫描所有的类,看看哪个类上面

@Component注解的,如果有规则如下

@Component或者@Component("person")

public class Person {

..............

}

@Component有很多写法,表示的意义不同,

@Repository写在dao上  @Service写在service@Controller写在控制器上

把注解下类名的第一个字母变小写,如果指定@Component("person")就按指定的自动生成

<bean id=”person” class=”..........”></bean>   (当然这个bean是不存在的,只不过原则上按照次方式来处理)

然后再按照属性有@Resource注解的规则进行赋值

 

 

 

 

 

 

转载于:https://www.cnblogs.com/lisihang/p/6683575.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值