@Scope的使用很简单,直接在类上加上就行
@PostConstruct:相当于xml配置方式的init-method方法
@PreDestroy:相当于xml配置方式的destroy-method方法
例如:userService
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
29
30
31
32
33
34
35
36
37
|
package
com.fz.annotation.service;
import
javax.annotation.PostConstruct;
import
javax.annotation.PreDestroy;
import
javax.annotation.Resource;
import
org.springframework.context.annotation.Scope;
import
org.springframework.stereotype.Component;
import
com.fz.annotation.dao.UserDao;
import
com.fz.xml.entity.User;
@Scope
(
"prototype"
)
public
class
UserService {
private
UserDao userDao;
public
void
userAdd(){
User user =
new
User();
user.setUsername(
"zhangsan"
);
user.setPassword(
"zhangsan"
);
userDao.userAdd(user);
}
public
UserDao getUserDao() {
return
userDao;
}
@Resource
(name=
"userDaoImpl"
)
public
void
setUserDao(UserDao userDao) {
this
.userDao = userDao;
}
@PostConstruct
public
void
init(){
System.out.println(
"init..."
);
}
@PreDestroy
public
void
destroy(){
System.out.println(
"destroy..."
);
}
}
|
applicationContext.xml配置很简单:
1
2
3
4
5
6
7
8
9
10
11
12
|
<?
xml
version
=
"1.0"
encoding
=
"UTF-8"
?>
xsi:schemaLocation="http://www.springframework.org/schema/beans
<
context:annotation-config
/>
<
context:component-scan
base-package
=
"com.fz.annotation"
></
context:component-scan
>
</
beans
>
|
测试代码:
1
2
3
4
5
6
7
8
9
|
@Test
public
void
getProperties(){
ClassPathXmlApplicationContext ctx =
new
ClassPathXmlApplicationContext(
"applicationContext_annotation.xml"
);
UserService userService = (UserService) ctx.getBean(
"userService"
);
UserService userService1 = (UserService) ctx.getBean(
"userService"
);
userService.userAdd();
System.out.println(userService == userService1);
ctx.destroy();
}
|
结果如下:
可以看出init还是执行了两次,两个对象也不是同一个对象,但是destroy同样还是不执行了。。。。