歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Spring中bean的初始化和銷毀之前的方法XML和注解的兩種形式

XML形式
package cn.xy;

public class StudentServiceImpl
{
 private StudentDao studentDao;

 public void init()
 {
  System.out.println("正在執行初始化的init方法");
 }

 public void save(Student s)
 {
  studentDao.insert(s);
 }
 
 
 public void destory()
 {
  System.out.println("正在執行銷毀之前的destory方法");
 }

 public StudentDao getStudentDao()
 {
  return studentDao;
 }

 public void setStudentDao(StudentDao studentDao)
 {
  this.studentDao = studentDao;
 }

}

<bean id="studentDao" class="cn.xy.StudentDao" />
<bean id="studentService" class="cn.xy.StudentServiceImpl" init-method="init" destory-method="destory">
 <property name="studentDao" ref="studentDao">
</bean>

注解形式

package cn.xy;

public class StudentServiceImpl
{
       
 private StudentDao studentDao;

 @PostConstruct
 public void init()
 {
  System.out.println("正在執行初始化的init方法");
 }

 public void save(Student s)
 {
  studentDao.insert(s);
 }
 
 @PreDestory
 public void destory()
 {
  System.out.println("正在執行銷毀之前的destory方法");
 }

 public StudentDao getStudentDao()
 {
  return studentDao;
 }

 @Resource
 public void setStudentDao(StudentDao studentDao)
 {
  this.studentDao = studentDao;
 }

}

Copyright © Linux教程網 All Rights Reserved