spring学习——scope属性

本文详细介绍了Spring框架中Bean的作用域设置,包括singleton和prototype两种常见类型。通过具体示例展示了不同作用域下Bean实例的生命周期特点及应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

scope属性

scope表示spring容器对一个bean的请求的处理方式,我们常用的设置值有:singleton(默认的)和prototype

singleton

在容器中,从请求bean到容器生命周期结束,有且仅有一个bean的实例,每次请求都返回这个,所以对应生命周期从创建到容器销毁

prototype

每次请求bean,容器都会给生成一个新的实例并返回,返回后容器就不负责这个实例的管理。实例的生命周期就给请求方去管理来。

我们看的简单的例子

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">

    <bean id="helloWorld" class="com.test.Car" scope="singleton">
        <property name="brand" value="Spring"/>
    </bean>

</beans>

Car类

public class Car {
    private String brand;
    private String color;
    private int maxSpeed;

    public Car() {
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getMaxSpeed() {
        return maxSpeed;
    }

    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }
}

调用程序

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

    public static void main(String[] args) throws Throwable {

        ApplicationContext ctx=new ClassPathXmlApplicationContext("file:applicationContext.xml");

        Car helloWorld=(Car) ctx.getBean("helloWorld",Car.class);

        Car helloWorld1=(Car) ctx.getBean("helloWorld",Car.class);

        System.out.println(helloWorld==helloWorld1);

        System.out.println(helloWorld.toString());
        System.out.println(helloWorld1.toString());
    }
}

输出

true
com.xxx.Car@49c342bd
com.xxx.Car@49c342bd

两次获取的实例都是同一个,我们把配置文件中的

scope="singleton"

修改成

scope="prototype"

后,输出如下:

false
com.xxx.Car@5aba9dff
com.xxx.Car@11dafee2

获取实例是不一样的

### Spring与MyBatis集成教程 #### 配置依赖项 为了使Spring Boot项目能够顺利使用MyBatis,需在`pom.xml`文件中加入必要的依赖。这包括Spring Boot Starter以及MyBatis的starter包。 ```xml <dependencies> <!-- Other dependencies --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!-- Database driver, e.g., MySQL Connector/J --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies> ``` 此部分配置确保了应用程序可以访问所需的库来执行SQL查询和其他数据库交互操作[^1]。 #### 数据源配置 接着,在`application.properties`或`application.yml`内定义数据源属性,以便连接到目标关系型数据库实例: 对于`.properties`文件: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ``` 而对于`.yml`格式,则如下所示: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC username: root password: password driver-class-name: com.mysql.cj.jdbc.Driver ``` 这些设置指定了JDBC URL、用户名、密码以及其他必要参数以建立与MySQL服务器之间的通信链接。 #### 创建实体和Mapper接口 假设有一个名为`User`的数据表,那么对应的Java Bean应该像这样设计: ```java public class User { private Long id; private String name; private Integer age; // Getters and Setters... } ``` 随后创建一个映射器接口用于描述针对该对象的操作方法签名;注意这里并不需要实现具体逻辑——它们会被动态代理处理。 ```java @Mapper public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User selectById(Long id); int insert(User record); boolean updateByPrimaryKeySelective(@Param("record") User record); void deleteByPrimaryKey(Long id); } ``` 上述代码片段展示了基本CRUD(Create Read Update Delete)函数声明方式之一。 #### 编写Service层业务逻辑 最后一步是在服务组件里调用之前准备好的DAO层完成实际的任务流控制和服务封装。 ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper mapper; public List<User> getAllUsers() { return mapper.selectAll(); } public Optional<User> getUserById(long userId) { return Optional.ofNullable(mapper.selectById(userId)); } // More service methods... } ``` 至此已经完成了整个基于Spring Boot平台下整合MyBatis框架的基础搭建过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值