1.复制xml到container/annotation下
2.新建Waiter类,构造函数,初始化以及销毁函数
3.在Waiter方法体前面加上@Component
4.xml中添加组件扫描代码
5.test1测试是否创建了bean,注意,xml中没有像之前一样去配置bean的id等属性,而是扫描组件方式,注意,组件扫描方式,那么bean的id即为该类名的小写
6.test2测试单例模式下只能创建一个bean对象,在Waiter方法体前面加上@Scope("prototype"),则为false
7.在Waiter的init方法前,destroy前分别加上@PostConstruct,@PreDestroy
8.将范围重新修改为单例模式,调用ac.close,test3测试bean的生命周期
9.test4测试不实例化bean,也会预实例化bean。在Waiter前加上@Lazy(true),则不再预实例化
Water.java:
package container.annotation;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component("wt")
//@Component
//@Scope("prototype")
@Scope("singleton")
@Lazy(true)
public class Waiter {
public Waiter() {
System.out.println("Waiter的无参构造器");
}
@PostConstruct
public void init(){
System.out.println("Waiter的init方法............");
}
@PreDestroy
public void destroy(){
System.out.println("Waiter的destroy方法............");
}
}
xml:
<!-- 开启组件扫描,容器会检查container.annotation包及其子包下面的所有的类,
如果这些类包含了特定的注解,就会将其作为一个bean来进行管理 -->
<context:component-scan
base-package="container.annotation"/>
TestCase:
package container.annotation;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestCase {
@Test
public void test1(){
String cfg = "container/annotation/applicationContext.xml";
ApplicationContext ac =
new ClassPathXmlApplicationContext(cfg);
//Waiter wt = ac.getBean("waiter",Waiter.class);
Waiter wt = ac.getBean("wt",Waiter.class);
System.out.println(wt);
}
@Test
public void test2(){
String cfg = "container/annotation/applicationContext.xml";
ApplicationContext ac =
new ClassPathXmlApplicationContext(cfg);
//id为类名首字母小写
Waiter wt = ac.getBean("waiter",Waiter.class);
Waiter wt2 = ac.getBean("waiter",Waiter.class);
System.out.println(wt==wt2);
}
@Test
public void test3(){
String cfg = "container/annotation/applicationContext.xml";
AbstractApplicationContext ac =
new ClassPathXmlApplicationContext(cfg);
Waiter wt = ac.getBean("waiter",Waiter.class);
ac.close();
}
@Test
public void test4(){
String cfg = "container/annotation/applicationContext.xml";
AbstractApplicationContext ac =
new ClassPathXmlApplicationContext(cfg);
}
}