◎筱米加步枪◎.Blog

Happy coding

Spring2.5常用注解

筱米加步枪 posted @ 2010年4月06日 05:20 in [ 开源框架 ] with tags spring , 2594 阅读

公司代码很多Spring注解,下午花了点时间学习了下。贴个小案例来使用这些注解:

学习的注解列表

@Component
@Service
@Repository
@Controller
@Autowired
@Qualifier
@Resource
@PostConstruct
 @PreDestroy

1.水果接口

/**
 * 水果接口
 * 
 * @author ChenST
 *
 */
public interface Fruit {
	/**
	 * 获取水果的名字
	 * @return
	 */
	public String getName();
}

2.苹果类

/**
 * 苹果
 * @author ChenST
 *
 */
@Service
public class Apple implements Fruit {

	/*
	 * (non-Javadoc)
	 * @see com.spring.annotation.Fruit#getName()
	 */
	public String getName() {
		return "苹果";
	}
}

3.梨类

/**
 * 梨
 * @author ChenST
 *
 */
@Service
public class Pear implements Fruit {

	public String getName() {
		return "梨";
	}
}

4.人类

/**
 * 人,拥有水果
 * @author ChenST
 *
 */
/*
 * @Service表示定义个Bean对象默认Bean的名字为
 * 类的第一个字母小写名字,例如Human为human
 * @Service("name")也可以自己指定名字name
 * ----------以下四种注解是等效的,只是意义不同
 * @Component 比较中立的类进行注释
 * @Service   表示服务层
 * @Repository表示持久层
 * @Controller表示控制层
 */
@Service
public class Human {
	
	/** 表示拥有水果 */
	/*@Autowired(required = false)表示不确定
	 *Spring容器中拥有某个类的Bean时候,这样Spring
	 *找不到这个Bean时也不报错
	 *
	 *@Autowired注解表示自动注入对象。在配置文件中需要配置
	 *<context:annotation-config />
     *<context:component-scan base-package="*"/>
     *
     *@Qualifier("apple")表示当这个fruit有两个实现类时
     *指定其中一个。负责会报错
     *
     *@Resource注释与Autowired差不多,Resource可以通过
     *name和type来指明要注入的类
	 */
	//@Autowired
	//@Qualifier("apple")
	//@Resource(name="apple")
	@Resource(type=Apple.class)
	private Fruit fruit;
	
	public void setFruit(Fruit fruit) {
		this.fruit = fruit;
	}

	/**
	 * 吃水果
	 */
	public void eat(){
		System.out.println("我在吃"+this.fruit.getName());
	}
	
	/*
	 * @PostConstruct表示Spring容器初始化后调用
	 */
	@PostConstruct
	public void eatBegin(){
		System.out.println("我要开始吃了");
	}
	
	/*
	 * @PreDestroy表示Spring容器销毁之前调用
	 */
	@PreDestroy
	public void eatFinish(){
		System.out.println("吃完了");
	}
}

5.测试类

/**
 * 测试类
 * 
 * @author ChenST
 *
 */
public class Test {
	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		Human human=(Human) ctx.getBean("human");
		human.eat();
	}
}

5.applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
	
    <!-- 自动注解配置 -->
    <context:annotation-config />
    <context:component-scan base-package="*" />
</beans>

6.运行结果

我要开始吃了
我在吃苹果
吃完了

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter