Spring框架的简介与IOC的初步使用

原始开发方式:请求-->Servlet-->Service-->多个Dao

1、spring框架作用

a、Spring Core(IOC功能)
b、Spring AOP功能

(管理组件对象,维护对象关系,最终目的,降低组件之间的耦合度)

c、Spring Web Mvc功能,实现了标准的MVC的结构功能
(MVC设计,目的:架构一个MVC结构的Web程序)


d、Spring整合其他技术,如整合Struts,hibernate,mybatis

Spring-->整合API-->调用原有的技术API-->在Spring中使用整合API 编程-->JDBCTemplate-->JdbcTemplate.update(Sql,params)

2、SpringIOC应用

a、管理对象
创建、初始化、释放资源

b、维护对象关系

c、搭建SpringIOC开发环境

--引入相关jar包
--在src添加applicationContext.xml配置文件

ApplicationContext:Spring容器-->applicationContext.xml--><bean>

3、Spring容器-->管理组件及其之间的关系

a、根据xml配置文件创建ApplicationContext容器对象

b、向applicationContext.xml中配置<bean>

c、使用getBean(id名)获取组件

4、利用IOC创建组件的三种方法

(1)使用构造方法,例如:new XXX()

public static void main(String[] args) {
//原始方式
//Calendar c = new GregorianCalendar(); String conf = "applicationContext.xml"; //创建容器对象 ApplicationContext ac = new ClassPathXmlApplicationContext(conf); Calendar c = ac.getBean("c1",Calendar.class); System.out.println(c); }

  xml配置方式:

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

例如:

    <!-- 采用new Calendar()调用构造方法产生实例 -->
    <bean id = "c1" class="java.util.GregorianCalendar">
    </bean>

(2)使用静态工厂方法,类似于我们以前使用Calendar.getInstance()方法获得一个实例

public static void main(String[] args) {
        //原始方式
        //Calendar c = Calendar.getInstance();
        String conf = "applicationContext.xml";
        //创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf); 
        Calendar c = ac.getBean("c2",Calendar.class);
        System.out.println(c);
            
    }

xml配置方式:

<bean id= ""    class=""   factory-method ="" ></bean>

例如:

<!-- 采用Calendar.newInstance()静态工厂方法产生实例 -->
    <bean id="c2" class="java.util.Calendar" factory-method="getInstance">
    </bean>

(3)采用对象工厂方法,例如使用一个Calendar对象的getTime方法获得一个Date对象

public static void main(String[] args) {
        //原始方式
        //Calendar c = Calendar.getInstance();
        //Date date = c.getTime();
        String conf = "applicationContext.xml";
        //创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf); 
        Date date = ac.getBean("date",Date.class);
        System.out.println(date);
            
    }

xml配置方式:<bean id = "" factory-bean= "" factory-method=""> </bean>

例如:

<!-- 通过对象工厂方法去创建对象 ,例如采用c2.getTime()方法去创建一个Date对象-->
    <bean id = "date" factory-bean="c2" factory-method="getTime">
    </bean>

 

posted @ 2018-08-01 16:34  梦里下起了雪  阅读(149)  评论(0编辑  收藏  举报