1.Bean的作用域,其实就是bean采用单例模式还是非单例模式 放在网络编程环境是指bean在http请求的作用范围的过程 !
在java类上加上@Scope注解,可以设置bean的作用范围
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | package com.oxygen.dao.impl; import com.oxygen.dao.BookDao; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; @Repository ( "bookDao" ) @Scope ( "prototype" ) public class BookDaoImpl implements BookDao { public void save() { System.out.println( "Book Dao Save..." ); } } |
2.bean的生命周期是指bean的初始化和销毁的过程。 这里自定义了bean的初始化和销毁方法,要用到javax.annotation这个包里的注解。 如果在IntelliJ Idea中发现没有这两个注解,也没法import javax.annotation包时,需要在pom文件中添加javax的依赖。
1 2 3 4 5 | < dependency > < groupId >javax.annotation</ groupId > < artifactId >javax.annotation-api</ artifactId > < version >1.3.2</ version > </ dependency > |
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | package com.oxygen.dao.impl; import com.oxygen.dao.BookDao; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @Repository ( "bookDao" ) @Scope ( "singleton" ) public class BookDaoImpl implements BookDao { public void save() { System.out.println( "Book Dao Save..." ); } @PostConstruct public void init() { System.out.println( "Book Dao init.." ); } @PreDestroy public void destroy() { System.out.println( "Book Dao destroy.." ); } } |
这个注解@PostConstruct 标记了谁是初始化方法。
这个注解@PreDestroy标记了谁是初始化方法。
加上这两个注解后Spring注解就能执行被它们标记的方法,单@PreDestory标记的方法则需要注意,它不会默认执行。
若需要执行@PreDestroy标记的方法,则需要关闭Spring容器或者关闭钩子(Hook)
ApplicationContext没有关闭容器的方法,我们用AnnotationConfigApplicationContext里面的close方法来关闭容器。
以下展示了关闭容器来调用销毁bean的方法。
1 2 3 4 | AnnotationConfigApplicationContext ctx= new AnnotationConfigApplicationContext(SpringConfig. class ); BookDao bookDao= (BookDao) ctx.getBean( "bookDao" ); bookDao.save(); ctx.close(); |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)