1 分别为@PostConstruct @PreDestroy 在UserService里面使用
@Component("userService")
public class UserService {
private UserDAO userDAO;
@PostConstruct
public void init() {
System.out.println("init");
}
public void add(User user) {
userDAO.save(user);
}
public UserDAO getUserDAO() {
return userDAO;
}
@Resource(name="u")
public void setUserDAO( UserDAO userDAO) {
this.userDAO = userDAO;
}
@PreDestroy
public void destroy() {
System.out.println("destroy");
}
}
2 在项目启动时会自动调用 init()方法 ,当执行时ctx.destroy();会调用desotry方法
public class UserServiceTest {
@Test
public void testAdd() throws Exception {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
ctx.destroy();
}
}
执行后打印
init
destroy