1.Scope注解—为自动检测的组件提供一个作用域
通常受Spring管理的组件,默认或者最常用的作用域是“singleton”。然而,有时也会需要其他的作用域。 因此Spring 2.5还引入了一个新的@Scope注解。只要在注解中提供作用域的名称就行了, 比如:
@Scope("prototype")
@Repository
public class MovieFinderImpl implements MovieFinder {
2.@PostConstruct与@PreDestroy
CommonAnnotationBeanPostProcessor 不只是能识别@Resource注解,而且也能识别 JSR-250 lifecycle注解。在 Spring 2.5 中,这些注解的描述请参看initialization callbacks 与 destruction callbacks节。CommonAnnotationBeanPostProcessor已经在 Spring 的ApplicationContext中注册,当一个方法带有这些注解之一时,将被在其生命周期与 Spring 生命周期接口的方法或者显式声明回调方法同一刻上调用。下面的例子里,缓存将预置于初始化与销毁阶段。
这两个注解与init-method、destroy-method相似。
public class CachingMovieLister {
//构造完成之后
@PostConstruct
public void populateMovieCache() {
// populates the movie cache upon initialization...
}
//容器销毁之前
@PreDestroy
public void clearMovieCache() {
// clears the movie cache upon destruction...
}
}
UserService类中
@Resource(name="u")
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@PostConstruct
public void init(){
System.out.println("init");
}
@PreDestroy
public void destroy() {
System.out.println("destroy");
}
test类
UserService service = (UserService) ctx.getBean("userService");
service.add(new User());
service.destroy();
这里有一点奇怪之处,test类中必需要调用destroy方法才能输出destroy。也就是说,每次运行时都会初始化容器,但不是运行结束后就销毁。
本文详细介绍了Spring框架中的@Scope注解,用于定义组件的作用域,并探讨了@PostConstruct与@PreDestroy注解如何实现对象的初始化和销毁过程。通过具体的代码示例展示了这些注解的应用场景。
1860

被折叠的 条评论
为什么被折叠?



