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的方法。

相关文章
|
1月前
|
Java 关系型数据库 MySQL
Spring Boot自动配置:魔法背后的秘密
Spring Boot 自动配置揭秘:只需简单配置即可启动项目,背后依赖“约定大于配置”与条件化装配。核心在于 `@EnableAutoConfiguration` 注解与 `@Conditional` 系列条件判断,通过 `spring.factories` 或 `AutoConfiguration.imports` 加载配置类,实现按需自动装配 Bean。
|
7天前
|
前端开发 Java 应用服务中间件
《深入理解Spring》 Spring Boot——约定优于配置的革命者
Spring Boot基于“约定优于配置”理念,通过自动配置、起步依赖、嵌入式容器和Actuator四大特性,简化Spring应用的开发与部署,提升效率,降低门槛,成为现代Java开发的事实标准。
|
3天前
|
XML 前端开发 Java
一文搞懂 Spring Boot 自动配置原理
Spring Boot 自动配置原理揭秘:通过 `@EnableAutoConfiguration` 加载 `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports` 中的配置类,结合 `@Conditional` 按条件注入 Bean,实现“开箱即用”。核心在于约定大于配置,简化开发。
107 0
|
1月前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
323 4
|
3月前
|
Java Spring 容器
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
787 0
|
15天前
|
JavaScript Java Maven
【SpringBoot(二)】带你认识Yaml配置文件类型、SpringMVC的资源访问路径 和 静态资源配置的原理!
SpringBoot专栏第二章,从本章开始正式进入SpringBoot的WEB阶段开发,本章先带你认识yaml配置文件和资源的路径配置原理,以方便在后面的文章中打下基础
141 3
|
15天前
|
Java 测试技术 数据库连接
【SpringBoot(四)】还不懂文件上传?JUnit使用?本文带你了解SpringBoot的文件上传、异常处理、组件注入等知识!并且带你领悟JUnit单元测试的使用!
Spring专栏第四章,本文带你上手 SpringBoot 的文件上传、异常处理、组件注入等功能 并且为你演示Junit5的基础上手体验
449 2
|
4月前
|
人工智能 Java 测试技术
Spring Boot 集成 JUnit 单元测试
本文介绍了在Spring Boot中使用JUnit 5进行单元测试的常用方法与技巧,包括添加依赖、编写测试类、使用@SpringBootTest参数、自动装配测试模块(如JSON、MVC、WebFlux、JDBC等),以及@MockBean和@SpyBean的应用。内容实用,适合Java开发者参考学习。
491 0
|
7月前
|
前端开发 Java 数据库
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 介绍
本课介绍Spring Boot集成Thymeleaf模板引擎。Thymeleaf是一款现代服务器端Java模板引擎,支持Web和独立环境,可实现自然模板开发,便于团队协作。与传统JSP不同,Thymeleaf模板可以直接在浏览器中打开,方便前端人员查看静态原型。通过在HTML标签中添加扩展属性(如`th:text`),Thymeleaf能够在服务运行时动态替换内容,展示数据库中的数据,同时兼容静态页面展示,为开发带来灵活性和便利性。
365 0
|
7月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
355 0

热门文章

最新文章