Spring的零配置

@Component:标注一个普通的Spring Bean类。

@Controller:标注控制器组件类。

@Service:标注业务逻辑组件类。

@Repository:标注DAO组件类。

@Scope:指定Bean的作用域。

@Resource:配置依赖。

@PostConstruct和@PreDestroy:定制Bean生命周期的行为。

@AutoWired:指定自动装配。

@Qualifier:指定精确装配。

 

bean.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"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- 自动搜索指定包及其子包下的所有Bean类 -->
    <context:component-scan base-package="com.lee">
    </context:component-scan>
</beans>

java类

package com.lee.bean.impl;

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

import org.springframework.stereotype.Component;

import com.lee.bean.Fruit;
import com.lee.bean.Person;

@Component("xiaoMing")
public class XiaoMing implements Person {

    private Fruit fruit;

    public void eat() {

        fruit.description();
        System.out.println("yummy!");
    }

    public Fruit getFruit() {
        return fruit;
    }

    @Resource(name = "pear")
    public void setFruit(Fruit fruit) {
        this.fruit = fruit;
    }
    
    @PostConstruct
    public void init(){
        
        System.out.println("init...");
    }
    
    @PreDestroy
    public void destroy(){
        
        System.out.println("destroy...");
    }

}

精确装配

    @Autowired
    @Qualifier("pear")
    public void setFruit(Fruit fruit) {
        this.fruit = fruit;
    }

 

posted @ 2014-05-15 15:18  harryV  阅读(390)  评论(0编辑  收藏  举报