zoukankan      html  css  js  c++  java
  • 使用注解的方式来定义bean的作用域 即实现单例或原型

    第一步:新建工程   SecondSpring

    文件目录结构如下:

    第二步:导入相应的spring  jar包

    略...

    第三步: 新建类

    AnnotationTest.java

    package com.xuzhiwen.spring4;
    
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Service;
    
    
    @Service
    @Scope("singleton")
    public class AnnotationTest {
        public String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }

    第四步: 新建配置文件

    common.xml

    <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-2.5.xsd">
    <import resource
    ="xmlfolder/app1.xml" /> <import resource="xmlfolder/innerbean.xml" /> <import resource="xmlfolder/singleton.xml" /> <import resource="xmlfolder/annotation.xml" />
    </beans>

    第五步:新建配置文件

    annotation.xml

    <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-2.5.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-2.5.xsd">
        
        <context:component-scan base-package="com.xuzhiwen.spring4" />
        
    </beans>    

    第六步: 编写测试类

    package com.xuzhiwen.spring4;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Test {
        public static void main(String[] args) {
            ApplicationContext app = new ClassPathXmlApplicationContext("common.xml");
            AnnotationTest test1 = (AnnotationTest) app.getBean("annotationTest");
            test1.setName("helloworld");
            
            
            AnnotationTest test2 = (AnnotationTest) app.getBean("annotationTest");
            System.out.println(test2.getName());
        }
    }

    第七步:运行结果如下

    注: 同理可实现原型

  • 相关阅读:
    Oracle中有大量的sniped会话
    Error 1130: Host '127.0.0.1' is not allowed to connect to this MySQL server
    汉字转换为拼音以及缩写(javascript)
    高效率随机删除数据(不重复)
    vs2010 舒服背景 优雅字体 配置
    mvc中的ViewData用到webfrom中去
    jquery ajax return值 没有返回 的解决方法
    zShowBox (图片放大展示jquery版 兼容性好)
    动感效果的TAB选项卡 jquery 插件
    loading 加载提示······
  • 原文地址:https://www.cnblogs.com/beibidewomen/p/7389437.html
Copyright © 2011-2022 走看看