spring注解方式配置以及spring4的泛型注入 (4)

首先,在用注解之前,先在配置文件中加入以下配置,在base-package下自动扫描目录及子目录的注解 ,具体可以下载我的代码查看,下文有连接

<context:component-scan base-package="com.hp.spring"></context:component-scan>

一、@Controller 注解控制层(action)

@Controller
public class UserAction {
    
    @Autowired
    private UsreService usreService; 
} 

其中@Autowired 注入依赖,此外,@Resource和@Inject注解与@Autowired 类似

二、@Service 注解服务层

@Service
public class UsreService {
    
    @Autowired
    private UserDao userDao;  
}

三、@Repository 持久层

@Repository
public class UserDao {
} 

四、spring4的泛型注入测试

1 创建两个实体User和Role

public class User {
} 

public class Role {
} 

2 baseDao抽取泛型基础curd

public class BaseDao<T> {
    public void save(T entity){
        System.out.println("Save:" + entity);
    }
}

3 两个实现类UserDao 和 RoleDao

@Repository
public class RoleDao extends BaseDao<Role>{
} 

@Repository
public class UserDao extends BaseDao<User>{
} 

4 baseService

public class BaseService<T> {
    @Autowired
    private BaseDao<T> dao;//这里会自动根据实际类型传入User或Role
    
    public void addNew(T entity){
        System.out.println("addNew by " + dao);
        dao.save(entity);
    }
}

5 UserService 和RoleService

@Service
public class RoleService extends BaseService<Role>{
} 

//若注解没有指定 bean 的 id, 则类名第一个字母小写即为 bean 的 id
@Service
public class UserService extends BaseService<User>{
} 

6 测试类

    public static void main(String[] args) {
        
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annotation.xml");
        
        UserService userService = (UserService) ctx.getBean("userService");
        userService.addNew(new User());
        
        RoleService roleService = (RoleService) ctx.getBean("roleService");
        roleService.addNew(new Role()); 
    }  

整个系列项目代码: http://git.oschina.net/nmc5/spring

posted @ 2016-09-18 15:28  hp柠檬茶  阅读(8563)  评论(0编辑  收藏  举报