一、前言

这篇随笔主要是记录IoC完全使用Annotation的过程。

二、架包以及资源

架包的引入,以及项目结构参考spring3.2.5学习(一)——spring环境配置以及IOC简介

三、配置环境

1.配置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.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd">
         
    <context:annotation-config/>
    <!-- 配置注解扫描 -->
    <context:component-scan base-package="com.cyrus.platform" />
    
</beans>

其中base-package为指定扫描路径,当前配置为扫描路径:com.cyrus.paltform下的类。

2.服务类TCyrusUserService注释

package com.cyrus.platform.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.cyrus.platform.dao.TCyrusUserDAO;
import com.cyrus.platform.model.TCyrusUser;

@Component("userService")
public class TCyrusUserService {
    private TCyrusUserDAO userDAO;
    
    
    public void save(TCyrusUser user){
        this.userDAO.save(user);
    }

    public TCyrusUserDAO getUserDAO() {
        return userDAO;
    }

    @Resource(name="userDAO")
    public void setUserDAO(TCyrusUserDAO userDAO) {
        this.userDAO = userDAO;
    }

}

其中@Component("userService") 类似于spring配置文件中bean标签,括号内的userService为bean标签中的name属性;@Resource相当于bean标签下的property属性配置,@Resource没有指定名称时,默认的搜寻规则为先查询类型,如果类型无法匹配,再查询名称。在@Resource中添加name属性则指定相关bean。

3.实现类TCyrusUserDAOImpl注释

package com.cyrus.platform.dao.impl;

import org.springframework.stereotype.Component;

import com.cyrus.platform.dao.TCyrusUserDAO;
import com.cyrus.platform.model.TCyrusUser;

@Component("userDAO")
public class TCyrusUserDAOImpl implements TCyrusUserDAO {

    @Override
    public void save(TCyrusUser user) {
        System.out.println("the user is saved!");
    }
}

三、测试

package com.cyrus.platform.service;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.cyrus.platform.model.TCyrusUser;

public class TCyrusUserServiceTest {

    @Before
    public void setUp() throws Exception {
    }

    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:resources/spring/**/application*.xml");
        TCyrusUserService service = context.getBean("userService",TCyrusUserService.class);
        TCyrusUser user = new TCyrusUser();
        service.save(user);
    }

}