1. 程式人生 > >Bean管理之配置(@PostConstruct、@PreDestroy、@Scope)

Bean管理之配置(@PostConstruct、@PreDestroy、@Scope)

package com.imooc.demo2;

import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component("bean1")
public class Bean1 {

    @PostConstruct
    public void init(){
        System.out.println("initBean...");
    }

    public void say(){
        System.out.println("say...");
    }

    @PreDestroy
    public void destory(){
        System.out.println("destoryBean...");
    }
}
<context:component-scan base-package="com.imooc" />
package com.imooc.demo2;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringDemo2 {

    @Test
    public void demo1(){
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        Bean1 bean1 = (Bean1)applicationContext.getBean("bean1");

        bean1.say();

        applicationContext.close();
    }
}
執行結果:
initBean...
say...
destoryBean...

package com.imooc.demo2;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("bean2")
@Scope("prototype")
public class Bean2 {

}
<context:component-scan base-package="com.imooc" />
package com.imooc.demo2;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringDemo2 {

    @Test
    public void demo2(){
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        Bean2 bean1 = (Bean2)applicationContext.getBean("bean2");
        Bean2 bean2 = (Bean2)applicationContext.getBean("bean2");

        System.out.println(bean1 == bean2);
    }
}
執行結果(Ps:預設為單例,所以true):
false

Ps:Bean例項化使用XML方式,屬性注入用@註解方式。