1.延迟加载

<bean />

  

@Configuration
public class Config1 {

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

  

2.Bean作用域

<bean />  //单例
<bean />  //原型

  

@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 />

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 />
<context:annotation-config />
</beans>

  效果一样。

 

相关文章:

  • 2022-12-23
  • 2022-01-12
  • 2021-12-31
  • 2022-12-23
  • 2021-11-06
  • 2021-08-16
  • 2021-05-01
  • 2023-04-06
猜你喜欢
  • 2021-07-25
  • 2021-04-18
  • 2021-09-21
  • 2021-04-27
  • 2022-01-30
  • 2022-01-18
  • 2022-12-23
相关资源
相似解决方案