Spring @Scope注解+Singleton Scope +@Component示例

x33g5p2x  于2022-10-06 转载在 Spring  
字(5.7k)|赞(0)|评价(0)|浏览(924)

在这篇文章中,我们将讨论如何使用@Scope注解来创建一个范围为单子的bean。

我们使用@Scope来定义@Component类或@Bean定义的范围。它可以是单例、原型、请求、会话、globalSession或一些自定义的范围。在这篇文章中,我们将通过一个例子来讨论单子的作用域。
当Spring Bean的作用域为单子时,Spring IoC容器就会为该Bean定义的对象创建一个确切的实例。

默认情况下,Spring IoC容器会将所有Bean创建并初始化为单例。但是我们可以使用元素的scope="singleton"属性或使用@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)注解将bean的范围定义为单子。
我们将使用基于注解(@Component)和基于Java的配置(@Bean)来演示这个例子。

Spring @Scope注解+Singleton Scope +@Component示例

让我们创建一个例子来演示在Spring应用程序中使用@Scope注解与Singleton Scope的用法。

使用的工具和技术

  • Spring Framework - 5.1.0.RELEASE
  • JDK - 8或更高版本
  • Maven - 3.2以上
  • IDE - Eclipse Mars/STS

创建一个简单的Maven项目

使用你喜欢的IDE创建一个简单的Maven项目,关于打包结构请参考下面的章节。如果你是maven新手,请阅读本文《如何创建一个简单的Maven项目》。

项目结构

下图显示了项目结构,供您参考。 

the pom.xml File

<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.javaguides.spring</groupId>
    <artifactId>spring-dependson-annotation</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <name>spring-scope-example</name>
    <url>http://maven.apache.org</url>

    <properties>
         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.0.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                 <version>3.5.1</version>
                 <configuration>
                     <source>1.8</source>
                     <target>1.8</target>
                 </configuration>
            </plugin>
        </plugins>
    </build>
</project>

创建MessageService接口,如下。

MessageService.java

package net.javaguides.spring.scope;

public interface MessageService {

    String getMessage();

    void setMessage(String message);
}

让我们创建TwitterMessageService类,实现MessageService接口。

TwitterMessageService.java

package net.javaguides.spring.scope;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class TwitterMessageService implements MessageService {

    private String message;

    @Override
    public String getMessage() {
        return message;
    }

    @Override
    public void setMessage(String message) {
        this.message = message;
    }
}

基于注解的配置 - AppConfig.java

在基于java的配置类中声明上述豆类。

package net.javaguides.spring.scope;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "net.javaguides.spring")
public class AppConfig {
 
}

@ComponentScan注解扫描@Component注解的类在basePackages属性指定的包中的所有bean。

运行中的Spring应用程序 - Application.java

让我们创建一个主类并运行一个应用程序。

package net.javaguides.spring.scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Application {
 public static void main(String[] args) {
  AnnotationConfigApplicationContext  context = new AnnotationConfigApplicationContext(AppConfig.class);
  MessageService messageService = context.getBean(MessageService.class);
  messageService.setMessage("TwitterMessageService Implementation");
  System.out.println(messageService.getMessage());
  
  MessageService messageService1 = context.getBean(MessageService.class);
  System.out.println(messageService1.getMessage());
  context.close();
 }
}

输出

TwitterMessageService Implementation
TwitterMessageService Implementation

让我们使用基于Java的配置与@Bean注解来开发同一个例子。

Spring @Scope 注解 + Singleton Scope + @Bean 示例

创建MessageService接口,如下所示。

MessageService.java

package net.javaguides.spring.scope;

public interface MessageService {

    String getMessage();

    void setMessage(String message);
}

让我们创建TwitterMessageService类,实现MessageService接口。

TwitterMessageService.java

package net.javaguides.spring.scope;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

public class TwitterMessageService implements MessageService {

    private String message;

    @Override
    public String getMessage() {
        return message;
    }

    @Override
    public void setMessage(String message) {
        this.message = message;
    }
}

基于注解的配置 - AppConfig.java

在基于java的配置类中声明上述豆类。

package net.javaguides.spring.scope;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class AppConfig {

    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
    public MessageService messageService() {
        return new TwitterMessageService();
    }
}

@ComponentScan注解扫描所有其类被@Component注解在由basePackages属性指定的包中的bean。

运行中的Spring应用程序 - Application.java

让我们创建一个主类并运行一个应用程序。

package net.javaguides.spring.scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Application {
 public static void main(String[] args) {
  AnnotationConfigApplicationContext  context = new AnnotationConfigApplicationContext(AppConfig.class);
  MessageService messageService = context.getBean(MessageService.class);
  messageService.setMessage("TwitterMessageService Implementation");
  System.out.println(messageService.getMessage());
  
  MessageService messageService1 = context.getBean(MessageService.class);
  System.out.println(messageService1.getMessage());
  context.close();
 }
}

输出

TwitterMessageService Implementation
TwitterMessageService Implementation

本文的源代码可在我的GitHub仓库https://github.com/RameshMF/spring-core-tutorial找到。

相关文章