Spring-基于注解的配置[03Bean作用范围和生命周期方法]

简介: Spring-基于注解的配置[03Bean作用范围和生命周期方法]

Bean的作用范围


通过注解配置的Bean和通过<bean>配置的Bean一样,默认的作用范围都是singleton。

Spring为注解配置提供了一个@Scope注解,可以通过它显示指定Bean的作用范围。


实例


代码已托管到Github—> https://github.com/yangshangwei/SpringMaster


20170730060741468.jpg

package com.xgj.ioc.configuration.lifeCycle;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Scope("prototype") 
@Component
public class Teacher {
    private Student student;
    /**
     * 
     * 
     * @Title:Teacher
     * 
     * @Description:构造函数
     */
    public Teacher() {
        super();
        System.out.println("Teacher is initing....");
    }
    @Autowired
    public void setStudent(Student student) {
        this.student = student;
    }
}
package com.xgj.ioc.configuration.lifeCycle;
import org.springframework.stereotype.Component;
@Component
public class Student {
    public Student() {
        super();
        System.out.println("Student is initing....");
    }
}

配置文件

<?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/context 
            http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- (1)声明Context命名空间以及Schema文件   (2)扫描类包以及应用注解定义的bean -->
    <context:component-scan base-package="com.xgj.ioc.configuration.lifeCycle"/>
</beans>


测试类

package com.xgj.ioc.configuration.lifeCycle;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ScopeTest {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "classpath:com/xgj/ioc/configuration/lifeCycle/beanLifeCycle.xml");
        System.out.println("isPrototype:" + ctx.isPrototype("teacher"));
        System.out.println("isSingleton:" + ctx.isSingleton("teacher"));
    }
}


运行结果:

20170730063722631.jpg

Bean的生命周期方法


@Scope注解通过入参指定Bean的作用范围。 在使用<bean>进行配置可以通过init-method和destory属性指定Bean的初始化及容器销毁前执行的方法。


Spring从2.5开始支持JSR-250中定义的@PostConstruct和PreDestory注解。 在Spring中这两个注解相当于init-method和destroy-method属性的功能。 不过在使用注解时,可以在一个bean 中定义多个@PostConstruct和@PreDestory方法。


实例


我们取消掉Teacher类的 @Scope(“prototype”) 注解 (因为对于singleton的Bean,容器管理,prototype由调用者管理,Spring不管理) ,增加 @PostConstruct 和PreDestory。

改造如下

package com.xgj.ioc.configuration.lifeCycle;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
//@Scope("prototype")
@Component
public class Teacher {
    private Student student;
    /**
     * 
     * 
     * @Title:Teacher
     * 
     * @Description:构造函数
     */
    public Teacher() {
        super();
        System.out.println("Teacher is initing....");
    }
    @Autowired
    public void setStudent(Student student) {
        this.student = student;
    }
    @PostConstruct
    public void init1() {
        System.out.println("init 1");
    }
    @PostConstruct
    public void init2() {
        System.out.println("init 2");
    }
    @PreDestroy
    public void destory1() {
        System.out.println("destory 1");
    }
    @PreDestroy
    public void destory2() {
        System.out.println("destory 2");
    }
}

测试类

package com.xgj.ioc.configuration.lifeCycle;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ScopeTest {
    public static void main(String[] args) {
        // 启动容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "classpath:com/xgj/ioc/configuration/lifeCycle/beanLifeCycle.xml");
        System.out.println("isPrototype:" + ctx.isPrototype("teacher"));
        System.out.println("isSingleton:" + ctx.isSingleton("teacher"));
        // 关闭容器,对于singleton的Bean,容器管理,prototype由调用者管理,Spring不管理
        ((ClassPathXmlApplicationContext) ctx).destroy();
    }
}


运行结果:


20170730064304100.jpg


由此可以看出,Spring先调用类的构造函数实例化Bean,然后在执行@Autowired进行自动注入,然后分别执行标注了@PostConstruct的方法,然后在容器关闭时,分别执行了标注@PreDestroy的方法。

相关文章
|
6天前
|
缓存 Java API
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
本文介绍了在Spring Boot中配置Swagger2的方法。通过创建一个配置类,添加`@Configuration`和`@EnableSwagger2`注解,使用Docket对象定义API文档的详细信息,包括标题、描述、版本和包路径等。配置完成后,访问`localhost:8080/swagger-ui.html`即可查看接口文档。文中还提示了可能因浏览器缓存导致的问题及解决方法。
39 0
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
|
6天前
|
Java 关系型数据库 数据库
微服务——SpringBoot使用归纳——Spring Boot事务配置管理——Spring Boot 事务配置
本文介绍了 Spring Boot 中的事务配置与使用方法。首先需要导入 MySQL 依赖,Spring Boot 会自动注入 `DataSourceTransactionManager`,无需额外配置即可通过 `@Transactional` 注解实现事务管理。接着通过创建一个用户插入功能的示例,展示了如何在 Service 层手动抛出异常以测试事务回滚机制。测试结果表明,数据库中未新增记录,证明事务已成功回滚。此过程简单高效,适合日常开发需求。
29 0
|
6天前
|
Java 数据库连接 数据库
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
37 0
|
6天前
|
缓存 Java 应用服务中间件
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——依赖导入和Thymeleaf相关配置
在Spring Boot中使用Thymeleaf模板,需引入依赖`spring-boot-starter-thymeleaf`,并在HTML页面标签中声明`xmlns:th=&quot;http://www.thymeleaf.org&quot;`。此外,Thymeleaf默认开启页面缓存,开发时建议关闭缓存以实时查看更新效果,配置方式为`spring.thymeleaf.cache: false`。这可避免因缓存导致页面未及时刷新的问题。
26 0
|
9月前
|
Java 开发者 Spring
解析Spring中Bean的生命周期
解析Spring中Bean的生命周期
81 2
|
9月前
|
XML druid Java
Spring5系列学习文章分享---第二篇(IOC的bean管理factory+Bean作用域与生命周期+自动装配+基于注解管理+外部属性管理之druid)
Spring5系列学习文章分享---第二篇(IOC的bean管理factory+Bean作用域与生命周期+自动装配+基于注解管理+外部属性管理之druid)
104 0
|
5月前
|
Java 开发者 Spring
Spring bean的生命周期详解!
本文详细解析Spring Bean的生命周期及其核心概念,并深入源码分析。Spring Bean是Spring框架的核心,由容器管理其生命周期。从实例化到销毁,共经历十个阶段,包括属性赋值、接口回调、初始化及销毁等。通过剖析`BeanFactory`、`ApplicationContext`等关键接口与类,帮助你深入了解Spring Bean的管理机制。希望本文能助你更好地掌握Spring Bean生命周期。
335 1
|
5月前
|
Java 开发者 Spring
Spring bean的生命周期详解!
本文详细介绍了Spring框架中的核心概念——Spring Bean的生命周期,包括实例化、属性赋值、接口回调、初始化、使用及销毁等10个阶段,并深入剖析了相关源码,如`BeanFactory`、`DefaultListableBeanFactory`和`BeanPostProcessor`等关键类与接口。通过理解这些核心组件,读者可以更好地掌握Spring Bean的管理和控制机制。
183 1
|
8月前
|
Java Spring 容器
Spring Boot 启动源码解析结合Spring Bean生命周期分析
Spring Boot 启动源码解析结合Spring Bean生命周期分析
146 11
|
7月前
|
前端开发 Java 开发者

热门文章

最新文章