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. 调用 指定初始化方法 init
  8. 如果存在类实现 BeanPostProcessor(处理Bean) ,执行postProcessAfterInitialization
  9. 执行业务处理
  10. 如果Bean实现 DisposableBean 执行 destroy
  11. 调用 指定销毁方法 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();

    }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值