Spring之在学习(3)

Bean的生命周期

生命周期详情

  1. instantiate bean对象实例化
  2. populate properties 封装属性
  3. 如果Bean实现BeanNameAware 执行 setBeanName
  4. 如果Bean实现BeanFactoryAware 或者 ApplicationContextAware 设置工厂 setBeanFactory 或者上下文对象 setApplicationContext
  5. 如果存在类实现 BeanPostProcessor(后处理Bean) ,执行postProcessBeforeInitialization
  6. 如果Bean实现InitializingBean 执行 afterPropertiesSet
  7. 调用<bean init-method="init"> 指定初始化方法 init
  8. 如果存在类实现 BeanPostProcessor(处理Bean) ,执行postProcessAfterInitialization
  9. 执行业务处理
  10. 如果Bean实现 DisposableBean 执行 destroy
  11. 调用<bean destroy-method="customerDestroy"> 指定销毁方法 customerDestroy

代码实现

测试代码,实现类:
package com.wanggs.pojo;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Created by wanggs on 2017/7/9.
 */
public class User implements BeanNameAware, ApplicationContextAware, InitializingBean, DisposableBean {
    public User() {
        System.out.println("1.构造方法执行");
    }

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        System.out.println("2 装载属性,调用setter方法");
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public void setBeanName(String name) {
        System.out.println("3.通过BeanNameAware接口,获得配置文件id属性的内容:" + name);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("4.通过ApplicationContextAware接口,获得Spring容器," + applicationContext);
    }

    /**
     * 5 在后处理bean MyBeanPostProcessor.java 处
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("6.通过InitializingBean,确定属性设置完成之后执行");
    }

    public void userInit() {
        System.out.println("7.配置init-method执行自定义初始化方法");
    }

    /**
     * 8  在后处理bean MyBeanPostProcessor.java 处
     */
    @Override
    public void destroy() throws Exception {
        System.out.println("9.通过DisposableBean接口,不需要配置的销毁方法");
    }

    public void userDestroy() {
        System.out.println("10.配置destroy-method执行自定义销毁方法");
    }


}

Spring 容器
<?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">

     <!-- 5 lifecycle 生命周期
        1.构造方法执行
        2 装载属性,调用setter方法
        3.通过BeanNameAware接口,获得配置文件id属性的内容:lifeUser
        4.通过ApplicationContextAware接口,获得Spring容器
        5. 实现BeanPostProcessor后处理,初始化前,执行postProcessBeforeInitialization方法
        6.通过InitializingBean,确定属性设置完成之后执行
        7.配置init-method执行自定义初始化方法
        8. 实现BeanPostProcessor后处理,在自定义初始化之后,执行postProcessAfterInitialization方法
        // 执行操作
        9.通过DisposableBean接口,不需要配置的销毁方法
        10.配置destroy-method执行自定义销毁方法

    -->
     <bean id="lifeUser" class="cn.itcast.d_lifecycle.User" init-method="userInit" destroy-method="userDestroy">
        <property name="username" value="jack"></property>
        <property name="password" value="1234"></property>
     </bean>
     <!-- 5.1配置 后处理bean -->
     <bean class="cn.itcast.d_lifecycle.MyBeanPostProcessor"></bean>
     
     
</beans>

测试
public class UserTest {

    @Test
    public void userTest() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User) applicationContext.getBean("user");
        System.out.println(user);
    }

}
运行结果

1.构造方法执行
2 装载属性,调用setter方法
3.通过BeanNameAware接口,获得配置文件id属性的内容:123456
3.通过BeanNameAware接口,获得配置文件id属性的内容:user
4.通过ApplicationContextAware接口,获得Spring容器,org.springframework.context.support.GenericApplicationContext@5a61f5df: startup date [Sun Jul 09 14:37:51 CST 2017]; root of context hierarchy
6.通过InitializingBean,确定属性设置完成之后执行
7.配置init-method执行自定义初始化方法
七月 09, 2017 2:37:51 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@491666ad: startup date [Sun Jul 09 14:37:51 CST 2017]; root of context hierarchy
七月 09, 2017 2:37:51 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
1.构造方法执行
2 装载属性,调用setter方法
3.通过BeanNameAware接口,获得配置文件id属性的内容:123456
3.通过BeanNameAware接口,获得配置文件id属性的内容:user
4.通过ApplicationContextAware接口,获得Spring容器,org.springframework.context.support.ClassPathXmlApplicationContext@491666ad: startup date [Sun Jul 09 14:37:51 CST 2017]; root of context hierarchy
6.通过InitializingBean,确定属性设置完成之后执行
7.配置init-method执行自定义初始化方法
com.wanggs.pojo.User@7f9fcf7f
9.通过DisposableBean接口,不需要配置的销毁方法

Process finished with exit code 0

Web开发应用Spring

pom依赖
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.9.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
配置web.xml文件
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>

    <!-- 设置给监听器xml配置文件的位置
          classpath: 表示src下
          直接写:表示WEB-INF下
      -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- 配置spring提供的监听器,加载 xml配置文件 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
<servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>com.wanggs.Controller.HelloServlet</servlet-class>
</servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Spring容器
<?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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="helloServlet" class="com.wanggs.Controller.HelloServlet"/>
</beans>
Servlet操作
package com.wanggs.Controller;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by wanggs on 2017/7/9.
 */
public class HelloServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //第一种方式获得
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        HelloServlet helloService = (HelloServlet) webApplicationContext.getBean("helloService");
        System.out.println(helloService);

        //第二种方式
        WebApplicationContext webApplicationContext2 = (WebApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        HelloServlet helloService2 = (HelloServlet) webApplicationContext2.getBean("helloService");
        System.out.println(helloService2);


    }
}

Spring整合Junit注解开发

pom依赖
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.9.RELEASE</version>
    </dependency>
测试
/**
 * Created by wanggs on 2017/7/7.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class BookServiceTest {
    @Autowired
    private BookServiceImpl bookService;

    @Test
    public void addBook() throws Exception {
        bookService.see();

    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,269评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,005评论 6 342
  • 什么是Spring Spring是一个开源的Java EE开发框架。Spring框架的核心功能可以应用在任何Jav...
    jemmm阅读 16,601评论 1 133
  • 夏婕第一次见到黎央央那天,上海正下着濛濛细雨,公交车站牌里的学生个个灰头土脸,头发上带着水珠,一个女孩子的妆...
    安生1996阅读 328评论 0 1
  • 断断续续用了两个星期把这本书啃完,并不是不听不用六爷的"30分快速阅读"的方法,而是这是一本干货满满的好书,需要...
    小嘛小二两阅读 1,479评论 1 3