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>
    

      效果一样。

  • 相关阅读:
    js中局域变量与全局变量的区别
    如何使用ps制作动态图片
    关于html页面中Input(文本框)控件OnChange事件的触发条件
    SQL常用语法汇总
    jsp六个动作详解
    ajax详解
    setTimeout与setTimeinterval的使用
    水晶报表在web应用程序中应用
    js字符串操作
    Documentum之基础(1)
  • 原文地址:https://www.cnblogs.com/lh218/p/6551188.html
Copyright © 2011-2022 走看看