spring总结之一(spring开发步骤、bean对象的管理、bean生命周期)

###spring

1.概念:开源,轻量级,简化开发的企业级框架。

开源:免费,发展快。
轻量级:占内存小。
简化开发:通用的功能封装,提高程序员的开发效率。
------------------------------------------------------------------
------------------------------------------------------------------

2.特点:

1)简化开发,提高开发效率
2)解耦
3) 集成第三方优秀的框架

------------------------------------------------------------------------------------------------------------------------------------

###spring容器(IOC容器)

Spring容器:Spring容器装bean对象的。(##Spring容器   bean工厂)

Bean:能创建对象的类。

 

开发步骤

1)创建maven  

2) 添加一个web.xml            (#比如   前端控制器的配置)

3) 添加tomcat

4) 在pom.xml里面添加.jar包(#各种jar包  spring-webmvc包   junit包)

Spring-webmvc
junit

    <dependencies>
    <!-- spring 的依赖jar包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.9.RELEASE</version>
    </dependency>
    <!-- junit测试jar包 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

  </dependencies>

5)写一个bean类(一个能创建对象的类)


package cn.sjl.spring.bean ;
public class HelloSpring{
    public void sayHello(){
        System.out.println("Hello Spring!");
    }
}

6)通过配置文件把bean交给容器

把配置文件application.xml文件放到resources文件夹下面。

<bean id="hello" class="cn.sjl.spring.bean"/>

7)从spring容器中获取bean 

a)获取容器对象
   AbstractApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");

b)从容器中获取bean对象

    //getBean方法的第一个参数:表示配置文件中的id名
    //...第二个参数:表示该类的Class类型的对象  用反射加载
  HelloSpring hello =  ac.getBean( "hello", HelloSpring.class);
hello.sayHello();

 

8)关闭容器

ac.close();
说明:测试类中用的较多。(单元测试)

------------------------------------------------------------------------------------------------------------------------------------

###spring管理bean对象的三种方式(面试题)

1.用无参的构造方法创建对象。(重点

   <bean id="配置文件中的id名" class="包名.类名";>

 

2.使用静态工厂实例化对象(了解)

静态工厂方法:使用静态方法获取对象的模式,叫静态工厂实例化对象
Calendar c = Calendar.getInstance();

<bean id="c" class="java.util.Calendar" factory-method="getInstance"/>

 

3.使用实例工厂方法实例化对象(了解)

cn.sjl.spring.bean
public class BeanFactory{
    public Calendar getC(){
        return Calendar.getInstance();
    }
}

先创建对象,然后调用方法
<bean id="factory" class="cn.sjl.spring.bean.BeanFactory"/>

<bean id="c1" factory-method="getC"  factory-bean="factory"/>
------------------------------------------------------------------------------------------------------------------------------------

### Bean的生命周期

生命周期:从创建到销毁过程,叫生命周期
public class BeanLife{
    public BeanLife(){
        ......("BeanLife");
    }
    public void init(){
        ......("init");
    }
    public void destroy(){
        ......("destroy);
    }
}

<bean id="beanLife" class="xx.xx.BeanLife"  init-method="init" destroy-method="destroy"/>
posted @ 2018-08-25 23:21  贰零一八  阅读(293)  评论(0编辑  收藏  举报