Spring认知

来源:互联网 发布:淘宝网汽车用品配件 编辑:程序博客网 时间:2024/06/05 13:35

概述

spring是一个开源框架,是为了解决企业应用程序开发复杂性而创建的,框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一种软件,同时为J2EE开发提供集成的框架
  • spring核心容器:核心容器提供spring框架的基本功能,核心容器的主要控件是BeanFactory,它是工厂模式的实现,BeanFactory使用控制反转(IoC)模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。

    spring的优点

  • 方便解耦,简化开发(高内聚低耦合)

    • spring就是一个容器,可以将所有对象创建和依赖注入,也可以将维护依赖关系交给spring管理。
    • spring工厂是用于生成bean,也就是静态工厂模式。
  • AOP编程的支持

    • spring提供面向切面编程(AOP),可以方便的实现对程序进行全线拦截,运行监控等功能。可以打印日志。
  • 声明式事务的支持(AOP动态代理)

    • 只需要通过配置就可以完成对事务的管理,无需手动编程,方便程序的测试。
  • spring对Junit4的支持

    • 可以通过注解方便的测试spring程序
    • 主要的注解有
      @RunWith(SpringJUnit4ClassRunner.class)
      @ContextConfiguration(“applicationContext.xml”)
实例代码    @RunWith(SpringJunit4ClassRunner.class)    @ContextConfiguraTion("appliacationContext.xml")    public class TestJunit{        @Rrsource        private Person person;        @Test        public void test(){            System.out.println(person);        }    }
  • 方便集成各种优秀框架

    • spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如struts2、Hibernate、Mybatis、Quartz(任务调度)等)的支持,还有Redis、搜索引擎(Solr)、消息队列(ActiveMQ)等。
  • 降低JavaEE API的使用难度

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

控制反转(IoC)

Spring设计的核心是org.springframework.beans包,它的设计目标是与Javabean组件一起使用,这个包通常不是由用户直接使用,而是由服务器将其用作其他多数功能的底层中介,下一个最高级抽象是BeanFactory接口,它是工厂设计模式的实现,允许通过名称创建和检索对象,BeanFactory也可以管理对象之间的关系。

IoC要导入的包
4个核心(beans、core、context、expression)
一个依赖(commons-loggings…jar)

  • 控制反转(IoC)的目标类
    • 提供service的接口和实现类
    • 获得service实现类的实例
  • 配置文件
    • 默认是applicationContext.xml,可以修改,并不是一定要用这个默认的,
    • 添加约束
      约束文件位置:spring-framework-XXX.RELEASE\docs\spring-framework-reference\html\ xsd-config.html
示例如下:    <?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>
  • 测试Ioc
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(“配置文件的路径”);UserService userService = (UserService) applicationContext.getBean("service");

依赖注入(DI)

类与类之间的依赖关系,有spring通过setter方法注入,这就是依赖注入
  • 依赖:一个对象需要使用另一个对象
  • 注入:通过setter方法进行另一个对象实例设置

依赖注入方式:手动装配和自动装配

  • 手动装配
    • 基于xml配置:setter方法、构造方法,P标签注入
    • 基于注解配置:@autowired @resource
  • 自动配置

    • autowire=”byType”//按类型装配
    • autowire=”byName”//按名称装配
    • constructor //构造装配
    • auto: //不确定装配

    构造方法

    属性: 用于配置构造方法一个参数argument
    name :参数的名称
    value:设置普通数据
    ref:引用数据,一般是另一个bean id值
    index :参数的索引号,从0开始 。如果只有索引,匹配到了多个构造方法时,默认使用第一个。
    type :确定参数类型两种注入方式

实例:使用名称name<constructor-arg name="name" value="王伟"></constructor-arg><constructor-arg name="interest" value="射击"></constructor-arg><constructor-arg name="sex" value="男"></constructor-arg>
实例:类型type和索引index<constructor-arg index="0" type="java.lang.String" value="王珂"></constructor-arg><constructor-arg index="1" type="java.lang.String" value="跑步"></constructor-arg><constructor-arg index="2" type="java.lang.String" value="女"></constructor-arg>

setter方法 ##

普通数据<bean id="car" class="com.yyx.bean.setter.Car">        <property name="name" value="保时捷"></property>        <property name="paizi" value="大大的保时捷"></property>        <property name="price" value="200000000"></property>    </bean>
引用数据<!-- dao层 --><bean id="userDao" class="com.yyx.bean.setter1.UserDaoImpl"></bean><!-- service层 --><bean id="userService" class="com.yyx.bean.setter1.UserServiceImpl"><property name="userDao" ref="userDao"></property></bean><!-- action层 --><bean id="userAction" class="com.yyx.bean.setter1.UserAction" scope="prototype"><property name="userService" ref="userService"></property></bean>

P命令空间 ##

  • 对“setter”方法进行简化,替换 property name=”属性名”,而是在bean p:属性名=“普通值” p:属性名-ref=“引用值”
  • p命名空间使用前提,必须添加命名空间
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:p="http://www.springframework.org/schema/p"    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">
实例:<bean id="userDao" class="com.yyx.bean.p.UserDaoImpl" p:name="张三"></bean><bean id="userService" class="com.yyx.bean.p.UserServiceImpl" p:userDao ref="userDao" ></bean><bean scope="prototype" id="userAction" class="com.yyx.bean.p.UserAction" p:userService-ref="userService"></bean>

集合注入##

  • 数组
property name="arr">            <array>                <value>乒乓球</value>                <value>篮球</value>                <value>足球</value>            </array></property>
  • 集合
<property name="list">            <list>                <value>basketball</value>                <value>football</value>                <value>baseball</value>            </list></property>
  • set
<property name="set">            <set>                <value>小苹果</value>                <value>最美的太阳</value>                <value>来生缘</value>                <value>红尘客栈</value>                <value>剑伤</value>                <value>天涯海角</value>            </set></property>
  • map
<property name="map">            <map>                <entry>                    <key><value>1</value></key>                    <value>傻傻的</value>                </entry>                <entry>                    <key><value>2</value></key>                    <value>痴痴的</value>                </entry>                <entry>                    <key><value>3</value></key>                    <value>呆呆的</value>                </entry>            </map></property>
  • properties
<property name="properties">            <props>                <prop key="jdbc.driverClass">com.mysql.jdbc.Driver</prop>                <prop key="jdbc.url">jdbs:mysql://localhost:3306/house</prop>                <prop key="jdbc.username">root</prop>                <prop key="jdbc.password">root</prop>            </props></property>

schema xml提示

  • 步骤1:确定xsd文件位置,spring-framework-3.2.0.RELEASE\schema\beans

  • 步骤2:复制路径:

<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">
  • 步骤3:搜索“xml.catalog”

  • 步骤4:添加约束提示

实例化bean(基于XML)

 实例化方式  
  • 默认构造
<bean id="" class=""></bean>//必须提供默认构造
  • 静态工厂

    用于生成实例对象,所有的方法必须是static
    常用与spring整合其他框架

<bean id="" class="工厂全限定类名" factory-method="静态方法" />
  • 实例工厂
    必须先有实例工厂对象,通过实例对象创建对象,提供所有的方法都是“非静态”的
<!--创建工厂实力--><bean id="myBeanFactoryId" class="工厂对象全路径"></bean>     <!-- 获得userService对象         确定工厂实例 factory-bean         确定普通方法 factory-method    --><bean id="userService" factory-bean="myBeanFactoryId" factory-method="createService"></bean>

注解

  注解:就是一个类,使用@注解名称,
  • @Component取代
<bean class="">
  • @Component(“id”) 取代
<bean id="" class="">
  • web开发,提供三个@Component衍生注解(功能一样)取代 bean class=””
    • @Repository :dao层
    • @Service:service层
    • @Controller:web层
  • 依赖注入:给私有字段设置,也可以给setter方法设置
    • 方式1:按照【类型】注入 @Autowired
    • 方式2:按照【名称】注入 @Resource(name=”名称”)
    • 方式3:按照类型注入(autowired)时,如果有两个匹配结果,会报错
      可以使用如下解决方案:
//@Autowired  //按照类型注入    但是,如果找到多个匹配的就会报错,expected single matching bean but found 2//@Qualifier("userServiceImpl2")  //按照名称注入
  • 注意:@Qualifier不能当独使用,一般配合autowired使用
    //@Autowired  按照类型注入    //@Qualifier("userServiceImpl")  //按照名称注入    @Resource(name="userServiceImpl")  //按照名称注入    private UserService userService;
//注入dao    @Autowired   //按照类型注入    public void setUserDao(UserDao userDao) {        this.userDao = userDao;    }
  • 生命周期
    初始化:@PostConstruct
    销毁: @PreDestroy

  • 作用域 (类前)
    @Scope(“prototype”) 多例

    注意:
    注解使用前提,导入aop的包,添加命名空间,让spring扫描含有注解类
    spring-aop-4.3.5.RELEASE.jar
    在配置文件中添加context标签

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context" 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    http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context.xsd">
<!--扫描含有注解的包--> <context:component-scan base-package="com.qf.annotation"></context:component-scan>
  • 普通属性有关的注解
    @value 注入属性值
    1、加在成员变量上:通过反射的Field赋值(破坏对象的封装性)
    @Value("刘三刀")    private String name;
2、加在set方法上:通过set方法赋值
    @Value("tom")    public void setName(String name) {        this.name = name;    }
  • @Value直接读取properties文件中的内容
 <!-- 扫描properties文件 --><context:property-placeholder location="classpath:dbinfo.properties"/>  <!—扫描一次-->   <!-- 扫描带有注解的包指定要扫描的包--><context:component-scan base-package="com.itqf"</context:component-scan>
  • b1在类中使用@value注解读取配置文件中的内容
    @value(“${properties配置文件中的key}”)
    @Value("${jdbc.driver}")    private String driver;    @Value("${jdbc.url}")    private String url;    @Value("${jdbc.username}")    private String username;    @Value("${jdbc.password}")    private String pwssword;