首页 > 代码库 > spring3.2.5学习(二)——IoC注解配置
spring3.2.5学习(二)——IoC注解配置
一、前言
这篇随笔主要是记录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); }}
spring3.2.5学习(二)——IoC注解配置
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。