zoukankan      html  css  js  c++  java
  • 吴裕雄天生自然SPRINGSpring Bean作用域

    在Spring中,不仅可以完成Bean的实例化,还可以为Bean指定作用域。在Spring中为Bean的实例定义了如表所示的作用域,通过@Scope注解来实现。

    演示Bean的作用域,具体步骤如下。
    
        1.使用Eclipse创建Web应用并导入JAR包
    
        2.编写不同作用域的Bean
    
        3.创建配置类
    
        4.创建测试类
    
        5.运行测试类
    package service;
    
    import org.springframework.stereotype.Service;
    
    @Service//默认为singleton相当于@Scope("singleton")
    public class SingletonService {
    
    }
    package service;
    
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Service;
    
    @Service
    @Scope("prototype")
    public class PrototypeService {
    
    }
    package config;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @ComponentScan("service")
    public class ScopeConfig {
    
    }
    package config;
    
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    import service.PrototypeService;
    import service.SingletonService;
    
    public class TestScope {
        public static void main(String[] args) {
            // 初始化Spring容器ApplicationContext
            AnnotationConfigApplicationContext appCon = new AnnotationConfigApplicationContext(ScopeConfig.class);
            SingletonService ss1 = appCon.getBean(SingletonService.class);
            SingletonService ss2 = appCon.getBean(SingletonService.class);
            System.out.println(ss1);
            System.out.println(ss2);
            PrototypeService ps1 = appCon.getBean(PrototypeService.class);
            PrototypeService ps2 = appCon.getBean(PrototypeService.class);
            System.out.println(ps1);
            System.out.println(ps2);
            appCon.close();
        }
    }

     

  • 相关阅读:
    打酱油
    一个在线演示代码运行的网站
    java数据结构之枚举
    tomcat ; nginx ;mysql
    restful demo 演示; jquery min1.1;
    rest规范 ; restful 风格; gradel介绍 ; idea安装 ;
    jetty;tomcat;热部署
    web容器 web服务器 servlet/jsp容器 之间的区别和关系是什么?
    jetty;linux 目录结构
    servlet;jsp;cookies;session
  • 原文地址:https://www.cnblogs.com/tszr/p/15310387.html
Copyright © 2011-2022 走看看