Spring Annotation(注解) @Scope ,@PostConstruct 和@PreDestroy

1.@Scope:

@Scope("prototype")或者@Scope("singleton")

就相当于applicationContext.xml里面bean的属性scope

scope="singleton">

2. @PostConstruct = init-method; @PreDestroy = destroy-method;

就相当于applicationContext.xml里面bean的属性

init-method="" destroy-method="">


StuDaoImpl代码:

package com.mth.impl;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.mth.bean.Student;
import com.mth.dao.IStuDao;

/**
 * 
 * @ClassName: StuDaoImpl
 * @Description: @Component("stuDao")起个名字叫做stuDao
 * @author mth [email protected]
 * @date 2014-1-19 下午10:13:23
 * 
 */
// bean属性里面的scope的注解表示方式,参数是singleton(一个)或者prototype(每次都创建一个新的)
@Scope("prototype")
@Component("stuDao")
public class StuDaoImpl implements IStuDao {

	@Override
	public void saveStu(Student stu) {
		System.out.println("保存学生");

	}

}

Service代码:

package com.mth.service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.mth.bean.Student;
import com.mth.dao.IStuDao;

@Component("stuSer")
public class Service {
	private IStuDao dao;

	// 在service初始化之前执行的方法 相当于配置文件里的init-method属性
	@PostConstruct
	public void init() {
		System.out.println("init");
	}

	public IStuDao getDao() {
		return dao;
	}

	// 指定当前需要注入的资源 与Component当中的值进行匹配
	@Resource(name = "stuDao")
	public void setDao(IStuDao dao) {
		this.dao = dao;
	}

	public void saveStu(Student student) {
		dao.saveStu(student);
	}

	// 相当于bean里面配置的destroy-method属性
	@PreDestroy
	public void destory() {
		System.out.println("destory");
	}
}

applicationContext.xml配置:



	
	

测试代码:

package com.mth.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mth.bean.Student;
import com.mth.service.Service;

public class Test {

	/**
	 * @Title: main
	 * @Description: 测试Spring注解
	 * @param @param args 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		// getBean参数 必须是service类上面@Component("stuSer")里面的参数
		Service service = (Service) context.getBean("stuSer");
		service.saveStu(new Student());
		context.destroy();
	}

}


你可能感兴趣的:(Spring)