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>

  效果一样。

 

posted @ 2017-03-14 22:37  lh_cn  阅读(763)  评论(0编辑  收藏  举报