因为Spring框架默认的是单例模式,并且是“饿汉式”的,我们可以通过注解@Lazy来配置为“懒汉式”的!
如果配置当前类中的生命周期处理,先要定义俩个方法,初始化方法和销毁方法,然后再在初始化方法前面添加@PostConstruct注解,在销毁方法前面添加@PreDestroy注解。(这两注解跟Spring无关,jre版本低的话是无法识别这两注解的!)
package cn.tedu.spring;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.stereotype.Repository;
@Repository
public class User {
public User() {
System.out.println("User.User()");
}
@PostConstruct
public void init() {
System.out.println("User.init()");
}
@PreDestroy
public void destroy() {
System.out.println("User.destroy()");
}
}
package cn.tedu.spring;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan("cn.tedu.spring")
public class SpringConfig {
}
package cn.tedu.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Demo {
public static void main(String[] args) {
//加载配置,获取Spring容器
System.out.println("开始获取Spring容器..");
AnnotationConfigApplicationContext ac =
new AnnotationConfigApplicationContext(SpringConfig.class);
System.out.println("获取容器成功!");
//从Spring中获取对象
System.out.println("准备获取对象...");
User user1 = ac.getBean("user",User.class);
User user2 = ac.getBean("user",User.class);
User user3 = ac.getBean("user",User.class);
System.out.println("对象获取成功!");
System.out.println("开始测试,,,");
System.out.println(user1);
System.out.println(user2);
System.out.println(user3);
System.out.println("测试成功!");
System.out.println("将要关闭...");
ac.close();
System.out.println("关闭成功!");
}
}