Spring 注解开发中bean作用范围与生命周期管理
bean作用范围@Scope
在注解开发中,bean的单例模式为@Scope("singleton"),而bean单例模式@Scope("prototype")
bookDaoImpl实现类
package com.itheima.dao.impl;
import com.itheima.dao.BookDao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
@Repository
@Scope("prototype")//单例为singleton
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("bookDao save ...");
}
@PostConstruct
public void init() {
System.out.println("init save ...");
}
public void destroy() {
System.out.println("destroy save ...");
}
}
main方法实现类
package com.itheima;
import com.itheima.config.SpringConfig;
import com.itheima.dao.BookDao;
import com.itheima.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App2 {
public static void main(String[] args) {
//1.加载配置类
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
//2.获取bean
BookDao bookDao = ctx.getBean(BookDao.class);
BookDao bookDao1 = ctx.getBean(BookDao.class);
//输出bean
System.out.println(bookDao);
System.out.println(bookDao1);
}
}
效果:
bean生命周期@PostConstruct与@PreDestroy
我们可以实现接口,来设定bean的生命周期,但是由于纯注解方式下,这个方法最好不要使用,
1.@PostConstruct//运行方法后实现的注解
2.@PreDestroy//彻底销毁前实现的注解
注意:(由于很多的原因,这两个注解如果没有出来的话,则就在Pom.xml文件里面添加个依赖,或者说把依赖的版本,升级到最新版本)
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
bookDaoImpl实现类
package com.itheima.dao.impl;
import com.itheima.dao.BookDao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Repository
@Scope("singleton")//单例为singleton
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("bookDao save ...");
}
@PostConstruct//运行方法后实现的方法,
public void init() {
System.out.println("init save ...");
}
@PreDestroy//彻底销毁前实现的方法
public void destroy() {
System.out.println("destroy save ...");
}
}
main方法实现类(把ApplicationContext改为AnnotationConfigApplicationContext,然后就可以实现关闭方法了)
package com.itheima;
import com.itheima.config.SpringConfig;
import com.itheima.dao.BookDao;
import com.itheima.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App2 {
public static void main(String[] args) {
//1.加载配置类
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
//2.获取bean
BookDao bookDao = ctx.getBean(BookDao.class);
BookDao bookDao1 = ctx.getBean(BookDao.class);
//输出bean
System.out.println(bookDao);
System.out.println(bookDao1);
//关闭容器
ctx.close();
}
}