Spring学习笔记(三)

本教程对应视频课程:http://edu.51cto.com/course/14731.htmlhtml

一、ioc和di

1.一、IOC容器

1.1.一、ObjectFactory 和ApplicationContext

BeanFactory:这个接口是spring中最底层的接口,只提供了最简单的IoC功能(建立bean,获取bean,销毁bean)java

在通常的应用当中,通常不使用BeanFactory;推荐用ApplicationContext(应用上下文);web

1.ApplicationContext继承了BeanFactory,提供了基本的IoC功能;spring

2.ApplicationContext还提供了其余功能,好比支持国际化,消息机制,统一的资源加载,AOP功能等apache

1.1.二、ApplicationContext的实现类

一、ClassPathXmlApplicationContext:读取classpath中的资源oracle

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

二、FileSystemXmlApplicationContextapp

ApplicationContext ac = new FileSystemXmlApplicationContext("c:/licationContext.xml");

三、XmlWebApplicationContextdom

XmlWebApplicationContext ac = new XmlWebApplicationContext();
// 须要指定ServletContext对象
ac.setServletContext(servletContext);
// 指定配置文件路径,开头的斜线表示Web应用的根目录
ac.setConfigLocation("/WEB-INF/applicationContext.xml"); 
// 初始化容器
ac.refresh();

1.1.二、Resource经常使用实现类

ClassPathResource:从classpath根路径开始找配置文件 ide

FileSystemResource:从磁盘的文件路径去找c://xx.xml测试

ServletContextResource:应用于web中,从web中去找配置文件

1.二、Bean的建立时机

1.ApplicationContext在加载的时候就会建立全部的bean(Web应用建议)

2.BeanFactory须要等到拿bean的时候才会建立bean(延迟加载)(桌面程序)

延迟加载

ApplicationContext作到延迟加载的效果:
针对于当前xml中全部的bean。

<beans default-lazy-init="default | false | true">

针对于指定的bean:

<beans lazy-init="default | false | true">

1.三、Bean的做用域

<bean id="" class="" scope="做用域"/>

singleton: 单例 :在Spring IoC容器中仅存在一个Bean实例 (默认的scope)

prototype: 多例 :每次从容器中调用Bean时,都返回一个新的实例,即每次调用getBean()时 ,至关于执行new 不会在容器启动时建立对象

对于MVC中的Action(Struts2)使用prototype类型,其余使用singleton

1.四、初始化和销毁方法

<bean id="someBean" class="......" 
        init-method="该类中初始化方法名" destroy-method="该类中销毁方法名">
</bean>

init-method:bean生命周期初始化方法,对象建立后就进行调用

destroy-method:容器被销毁的时候,若是bean被容器管理,会调用该方法。

若是bean的scope="prototype",那么容器只负责建立和初始化,它并不会被spring容器管理。

1.五、Bean的实例化的方式

1.5.一、构造器

构造器实例化,最标准,使用最多

java类

public class SomeBean1 {}

xml配置

<bean id="someBean1" class="SomeBean1全限定名"/>

1.5.二、静态工厂方式

java类

public class SomeBean2Factory {
    public static SomeBean2 getSomeBean2(){
        return new SomeBean2();
    }
}
public class SomeBean2 {}

xml配置

<bean id="someBean2" class="SomeBean2Factory全限定名" factory-method="getSomeBean2"/>

此时咱们经过上下文对象获取id为someBean2的对象,这个对象的类型为SomeBean2

1.5.三、实例工厂方式

实例工厂方法实例化:解决系统遗留问题,有点麻烦,使用比较少

public class SomeBean3 {}
public class SomeBean3Factory {
    public SomeBean3 getSomeBean3() {
        return new SomeBean3();
    }
}

xml配置

<bean id="someBean3Factory" class="SomeBean3Factory全限定名"/>
<bean id="someBean3" factory-bean="someBean3Factory" factory-method="getSomeBean3"/>

此时咱们获取id为someBean3的对象,实际上会建立实例工厂,而后在经过实例工厂的工厂方法来或者SomeBean3的对象

1.5.四、实现FactoryBean接口实例化

java类

public class SomeBean4 {}
public class SomeBean4FactoryBean implements FactoryBean<SomeBean4>{
     //返回对象
    public SomeBean4 getObject() throws Exception {
        return new SomeBean4();
    }
     //返回对象的类型
    public Class<?> getObjectType() {
        return SomeBean4.class;
    }
     //返回是否单例
    public boolean isSingleton() {
        return true;
    }
}

xml配置

<bean id="someBean4" class="SomeBean4FactoryBean全限定名" />

1.六、DI和ioc介绍

IoC(inverse of control):指将对象的建立权,反转到Spring容器;

DI (Dependency Injection) :指Spring建立对象的过程当中,将对象依赖属性经过配置进行注入 。

其实它们是同一个概念的不一样角度描述。DI相对IoC而言,明确描述了”被注入对象依赖IoC容器配置依赖对象”。

1.6.一、注入方式

使用setter注入:

1.使用bean元素的property子元素设置;

​ 简单类型值,直接使用value赋值;

​ 引用类型,使用ref赋值;

​ 集合类型,直接使用对应的集合类型元素便可。

2.spring经过属性的setter方法注入值;

3.在配置文件中配置的值都是string,spring能够自动的完成类型的转换

4.属性的设置值是在init方法执行以前完成的

构造器注入

1.spring在实例化对象的时候,若是对象没有配置constructor-arg,则使用默认的构造器实例化对象

2.若是有constructor-arg,那么spring使用这些constructor-arg来惟一肯定一个构造器

1.6.二、注入值的类型

一、简单类型数据

java类编写

public class Employee {
    private String name;
    private Integer age;
    private Double salary;
    private URL url;
       省略setter/getter
}

xml配置

<bean id="employee" class="cn.org.kingdom.vo.Employee">
        <property name="name" value="kingdom" />
        <property name="age" value="17" />
        <property name="salary" value="123" />
        <property name="url" value="http://urlValue" />
</bean>

2.对象类型的值

java类

public class EmpDAO {
    public void save(){
        System.out.println("EmpDAO.save()");
    }
}
public class EmpService {
    private EmpDAO dao;//持有一个引用数据类型

    public void setDao(EmpDAO dao) {
        this.dao = dao;
    }

    public void save() {
        dao.save();
        System.out.println("EmpService.save()");
    }
}

xml文件配置

<bean id="empDAO" class="cn.org.kingdom.vo.EmpDAO" />
<bean id="empService" class="cn.org.kingdom.vo.EmpService">
        <property name="dao" ref="empDAO" />
</bean>

3.注入集合类型

java类

public class ConnectionBean {
    private Set<String> set;
    private List<String> list;
    private String[] array;
    private Map<String, String> map;
    private Properties prop;
       省略setter/getter
}

xml文件配置

<bean id="collectionBean" class="cn.org.kingdom.dbc.ConnectionBean">
        <property name="set">
            <set>
                <value>set1</value>
                <value>set2</value>
                <value>set3</value>
            </set>
        </property>
        <property name="list">
            <list>
                <value>list1</value>
                <value>list2</value>
                <value>list3</value>
            </list>
        </property>
        <property name="array">
            <list>
                <value>array1</value>
                <value>array2</value>
                <value>array3</value>
            </list>
        </property>
        <property name="map">
            <map>
                <entry key="key1" value="value1"/>
                <entry key="key2" value="value2"/>
                <entry key="key3" value="value3"/>
            </map>
        </property>
        <property name="prop">
            <props>
                <prop key="pKey1">pVal1</prop>
                <prop key="pKey2">pVal2</prop>
                <prop key="pKey3">pVal3</prop>
            </props>
        </property>
    </bean>

1.七、属性占位符

一、添加jar包

使用DataSource的案例,给数据源注入Property中的数据加入相关jar包支持

commons-dbcp-1.2.2.jar、commons-pool-1.5.3.jar、com.springsource.oracle.jdbc-10.2.0.2.jar

二、引入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
        ">
</beans>

三、拷贝db.properties文件

db.driver=oracle.jdbc.driver.OracleDriver
db.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
db.username=scott
db.password=tiger

四、加载配置文件

<context:property-placeholder location="classpath:db.properties"/>
<bean id = "ds" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${db.driver}"></property>
        <property name="url" value="${db.url}"></property>
        <property name="username" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
</bean>

五、测试

package cn.org.kingdom.test;
import org.apache.commons.dbcp.BasicDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4Cla***unner;
@RunWith(SpringJUnit4Cla***unner.class)
@ContextConfiguration
public class SpringTest {
    @Autowired
    private BeanFactory factory;
    @Autowired
    private AbstractApplicationContext ctx ; 
    @Test
    public void testSpringTest() throws Exception {
        BasicDataSource ds = (BasicDataSource) ctx.getBean("ds");
        System.out.println(ds.getConnection());
    }
}
相关文章
相关标签/搜索