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>
    

      效果一样。

  • 相关阅读:
    第十五章:Android 调用WebService(.net平台)
    第十四章:样式(Style)和主题(Theme)
    第十三章:常用控件下
    第十三章:常用控件上
    第十二章:Android数据存储(下)
    第十一章:Android数据存储(上)
    第十章:Intent详解
    PHP7.X连接SQLSERVER数据库(CENTOS7)
    CentOs install oracle instant client
    softmax
  • 原文地址:https://www.cnblogs.com/lh218/p/6551188.html
Copyright © 2011-2022 走看看