代码改变世界

spring-06

2018-11-06 22:43  crow!  阅读(130)  评论(0编辑  收藏  举报

annotation

applicationContext.xml

引入 

xmlns:context="http://www.springframework.org/schema/context"

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd

<!-- 表示在当前的配置中 ,将采用Annotation注解的方式进行定义 -->
<context:annotation-config />
<!-- 定义扫描包,在此包中定义的所有程序类支持Annotation配置 -->
<context:component-scan base-package="cn.mldn" />

这三个名字不一样,但本质一样
如果定义的是DAO子类,建议使用 @Component
如果定义的是Service子类,建议使用 @Service
如果定义的是Action类,建议使用 @Repository

第一种方式:

    private IDeptDAO deptDAO ;
    public IDeptDAO getDeptDAO() {
        return deptDAO;
    }
    // 此时表示在整个Spring之中自动找到名称为deptDAOImpl的子类对象实例进行引用传递
    @Resource(name="deptDAOImpl")
    public void setDeptDAO(IDeptDAO deptDAO) {
        this.deptDAO = deptDAO;
    }

第二种方式

    // 自动根据类型引用
    @Resource
    private IDeptDAO deptDAO ;

测试代码:

IDeptDAO
package cn.mldn.dao;

import cn.mldn.vo.Dept;

public interface IDeptDAO {
    public boolean doCreate(Dept vo) ;
}
DeptDAOImpl 
package cn.mldn.dao.impl;
import org.springframework.stereotype.Component;
import cn.mldn.dao.IDeptDAO;
import cn.mldn.vo.Dept;
// 此时就相当于在,applicationContext.xml文件中定义<bean> ,id是deptDAOImpl
@Component
public class DeptDAOImpl implements IDeptDAO {

    @Override
    public boolean doCreate(Dept vo) {
        System.out.println("[DeptDAOImpl子类],数据的增加:" + vo);
        return true;
    }
}
IDeptService 
package cn.mldn.service;

import cn.mldn.vo.Dept;

public interface IDeptService {
    public boolean add(Dept vo) ;
}
DeptServiceImpl 
package cn.mldn.service.impl;

import javax.annotation.Resource;
import org.springframework.stereotype.Service;

import cn.mldn.dao.IDeptDAO;
import cn.mldn.service.IDeptService;
import cn.mldn.vo.Dept;

@Service
public class DeptServiceImpl implements IDeptService {

    // 自动根据类型引用
    @Resource
    private IDeptDAO deptDAO ;

    @Override
    public boolean add(Dept vo) {
        return this.deptDAO.doCreate(vo);
    }
}

test

    public static void main(String[] args) {

        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "applicationContext.xml");

        IDeptService service = ctx.getBean("deptServiceImpl" ,IDeptService.class) ;
        
        Dept vo = new Dept() ;
        vo.setDeptno(10);
        vo.setDname("kai fa bu");
        vo.setLoc("bei jing");
        
        System.out.println(service.add(vo));
    }

result

[DeptDAOImpl子类],数据的增加:Dept [deptno=10, dname=kai fa bu, loc=bei jing]
true