zoukankan      html  css  js  c++  java
  • Spring基础(8) : 延迟加载,Bean的作用域,Bean生命周期

    1.延迟加载

    <bean id="p" class="com.Person" lazy-init="true"/>
    

      

    @Configuration
    public class Config1 {
    
        @Bean("p")
        @Lazy(true)
        public Person getPerson(){
            return new Person();
        }
    }
    

      

    2.Bean作用域

    <bean id="p" class="com.Person" scope="singleton"/>  //单例
    <bean id="p" class="com.Person" scope="prototype"/>  //原型

      

    @Configuration
    public class Config1 {
    
        @Bean("p1")
        @Scope("prototype")
        public Person getP1(){
            return new Person();
        }
    
        @Bean("p2")
        @Scope("singleton")
        public Person getP2(){
            return new Person();
        }
    }
    

      

    3.生命周期

    public class Person {
        public void init(){
            System.out.println("init ");
        }
        public void destory(){
            System.out.println("destory ");
        }
    }
    
     <bean id="p" class="com.Person" init-method="init" destroy-method="destory"/>
    
    public static void main(String[] args){
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("a.xml");
            Person p = context.getBean("p",Person.class);
            context.close();
        }
    

    打印:

    init
    destory

    public class Person {
        @PostConstruct
        public void init(){
            System.out.println("init ");
        }
        @PreDestroy
        public void destory(){
            System.out.println("destory ");
        }
    }
    
    public static void main(String[] args){
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("a.xml");
            Person p = context.getBean("p",Person.class);
            context.close();
        }
    

      

    <?xml version="1.0" encoding="UTF-8" ?>
    <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-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    
    <bean id="p" class="com.Person"/>
    <context:annotation-config />
    </beans>
    

      效果一样。

  • 相关阅读:
    Ubuntu格式化分区时的一个小错误
    VS 2013中的新特性browser link
    回车登录,兼容
    ASP.NET MVC 站点设置.html 为起始页
    WebBrowser 禁用右键
    C# 获取时间差(几天前,几小时前,几分钟前,几秒前)
    JavaScrip操作Cookie
    JS生成GUID算法
    老李推荐: 第3章2节《MonkeyRunner源码剖析》脚本编写示例: MonkeyDevice API使用示例 4
    老李推荐: 第3章2节《MonkeyRunner源码剖析》脚本编写示例: MonkeyDevice API使用示例 3
  • 原文地址:https://www.cnblogs.com/lh218/p/6551188.html
Copyright © 2011-2022 走看看