Spring之在學習(3)

Bean的生命周期

生命周期詳情

  1. instantiate bean對象實例化
  2. populate properties 封裝屬性
  3. 如果Bean實現(xiàn)BeanNameAware 執(zhí)行 setBeanName
  4. 如果Bean實現(xiàn)BeanFactoryAware 或者 ApplicationContextAware 設置工廠 setBeanFactory 或者上下文對象 setApplicationContext
  5. 如果存在類實現(xiàn) BeanPostProcessor(后處理Bean) ,執(zhí)行postProcessBeforeInitialization
  6. 如果Bean實現(xiàn)InitializingBean 執(zhí)行 afterPropertiesSet
  7. 調(diào)用<bean init-method="init"> 指定初始化方法 init
  8. 如果存在類實現(xiàn) BeanPostProcessor(處理Bean) ,執(zhí)行postProcessAfterInitialization
  9. 執(zhí)行業(yè)務處理
  10. 如果Bean實現(xiàn) DisposableBean 執(zhí)行 destroy
  11. 調(diào)用<bean destroy-method="customerDestroy"> 指定銷毀方法 customerDestroy

代碼實現(xiàn)

測試代碼,實現(xiàn)類:
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.構造方法執(zhí)行");
    }

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        System.out.println("2 裝載屬性,調(diào)用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屬性的內(nèi)容:" + 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,確定屬性設置完成之后執(zhí)行");
    }

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

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

    public void userDestroy() {
        System.out.println("10.配置destroy-method執(zhí)行自定義銷毀方法");
    }


}

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.構造方法執(zhí)行
        2 裝載屬性,調(diào)用setter方法
        3.通過BeanNameAware接口,獲得配置文件id屬性的內(nèi)容:lifeUser
        4.通過ApplicationContextAware接口,獲得Spring容器
        5. 實現(xiàn)BeanPostProcessor后處理,初始化前,執(zhí)行postProcessBeforeInitialization方法
        6.通過InitializingBean,確定屬性設置完成之后執(zhí)行
        7.配置init-method執(zhí)行自定義初始化方法
        8. 實現(xiàn)BeanPostProcessor后處理,在自定義初始化之后,執(zhí)行postProcessAfterInitialization方法
        // 執(zhí)行操作
        9.通過DisposableBean接口,不需要配置的銷毀方法
        10.配置destroy-method執(zhí)行自定義銷毀方法

    -->
     <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.構造方法執(zhí)行
2 裝載屬性,調(diào)用setter方法
3.通過BeanNameAware接口,獲得配置文件id屬性的內(nèi)容:123456
3.通過BeanNameAware接口,獲得配置文件id屬性的內(nèi)容: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,確定屬性設置完成之后執(zhí)行
7.配置init-method執(zhí)行自定義初始化方法
七月 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.構造方法執(zhí)行
2 裝載屬性,調(diào)用setter方法
3.通過BeanNameAware接口,獲得配置文件id屬性的內(nèi)容:123456
3.通過BeanNameAware接口,獲得配置文件id屬性的內(nèi)容: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,確定屬性設置完成之后執(zhí)行
7.配置init-method執(zhí)行自定義初始化方法
com.wanggs.pojo.User@7f9fcf7f
9.通過DisposableBean接口,不需要配置的銷毀方法

Process finished with exit code 0

Web開發(fā)應用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>

    <!-- 設置給監(jiān)聽器xml配置文件的位置
          classpath: 表示src下
          直接寫:表示W(wǎng)EB-INF下
      -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- 配置spring提供的監(jiān)聽器,加載 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注解開發(fā)

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();

    }

}
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,545評論 19 139
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,268評論 6 342
  • 什么是Spring Spring是一個開源的Java EE開發(fā)框架。Spring框架的核心功能可以應用在任何Jav...
    jemmm閱讀 16,771評論 1 133
  • 夏婕第一次見到黎央央那天,上海正下著濛濛細雨,公交車站牌里的學生個個灰頭土臉,頭發(fā)上帶著水珠,一個女孩子的妝...
    安生1996閱讀 339評論 0 1
  • 斷斷續(xù)續(xù)用了兩個星期把這本書啃完,并不是不聽不用六爺?shù)?quot;30分快速閱讀"的方法,而是這是一本干貨滿滿的好書,需要...
    小嘛小二兩閱讀 1,502評論 1 3

友情鏈接更多精彩內(nèi)容