Spring的applicationContext配置文件中<bean>标签的属性说明

本文介绍 Spring 框架中 Bean 的生命周期配置,包括 singleton 和 prototype 两种作用域的区别,以及如何通过 init-method 和 destroy-method 属性来指定初始化和销毁方法。
首先看如下代码:
<bean name="user" class="com.domain.User" scope="singleton" init-method="init" destroy-method="destory"></bean>
在bean的配置当中的属性:
  1. id,(早期的属性,不推荐使用)id的值必须符合id的特性,唯一且不能使用特殊字符
  2. name,(建议使用)给对象起个名字,建议使用简单类名
  3. class,填写类的完整的全路径名称(限定名)
  4. scope,决定对象的声明周期,值有5种:
    1. singleton(默认值):单例。对象会在容器启动时创建,且getBean时只能得到一个实例。
    2. prototype:原型多例。对象会在使用时才开始创建,创建之后spring不在管理后续的声明周期,每次getBean时都会获得一个新的实例。
    3. request(很少使用):WEB项目中,Spring创建一个Bean对象,将对象存入到request域中。
    4. session(很少使用):WEB项目中,Spring创建一个Bean对象,将对象存入到session域中。
    5. globalSession(很少使用):WEB项目中,应用在Porlet环境。如果没有Porlet环境那么globalSession相当于session。
  5. init-method:指定初始化的方法。创建对象实例之后调用初始化方法。
  6. destory-method:指定销毁的方法。
    scope=“singleton”时,在容器销毁和销毁对象前调用销毁方法。
    scope=“prototype”时,永远不会调用销毁方法。
<profiles> <profile> <id>prod</id> <properties> <spring.profiles.active>prod</spring.profiles.active> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <excludes> <exclude>application.yml</exclude> </excludes> </configuration> </plugin> </plugins> </build> </profile> <profile> <id>dev</id> <properties> <spring.profiles.active>dev</spring.profiles.active> </properties> <activation> <activeByDefault>true</activeByDefault> </activation> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <executable>true</executable> <classifier>web-exec</classifier> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <excludes> <exclude>application.yml</exclude> </excludes> </configuration> </plugin> </plugins> </build> </profile> <profile> <id>test</id> <properties> <spring.profiles.active>test</spring.profiles.active> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <executable>true</executable> <classifier>web-exec</classifier> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <excludes> <exclude>application.yml</exclude> </excludes> </configuration> </plugin> </plugins> </build> </profile> </profiles> 可以优化一下吗
最新发布
10-31
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值