Spring2.5注解实例+Junit4注解测试方法
Eclipse导入jar文件,spring-test.jar,spring.jar(版本2.5),junit-4.4.jar
Spring的IOC注入的方式有:setter方式,构造函数方式,注解方式。
注解方式可以在xml文件中对整个文件夹的bean配置,注入的时候通过注解标签调用,使代码更加简洁,易于维护。
通过一个简单的例子+测试来说明:
dao.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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:component-scan base-package="org.zlex.spring.dao" /> </beans>
context:component-scan配置包的路径。
AccountDao.java
package org.zlex.spring.dao; import org.zlex.spring.domain.Account; public interface AccountDao { /** * 读取用户信息 * * @param username * @return */ Account read(String username); }
AccountDaoImpl.java
package org.zlex.spring.dao.impl; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; import org.zlex.spring.dao.AccountDao; import org.zlex.spring.domain.Account; @Component("accountDao") public class AccountDaoImpl implements AccountDao { public Account read(String username) { return new Account(username,"wolf"); } }
@Component注解表示bean的名字为accountDao,可以写成其他的名字。
@Repository注解作用同上,但是bean的名字同类名,方法名第一个字母小写。
Test.java测试类
package org.zlex.spring.test; import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.zlex.spring.dao.AccountDao; import org.zlex.spring.domain.Account; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:dao.xml"}) public class Test2 extends AbstractJUnit4SpringContextTests { @Autowired AccountDao accountDao; @Before public void setUp() throws Exception{ System.out.println("setUp ..."); } @After public void tearDown() throws Exception{ System.out.println("tearDown ..."); } @org.junit.Test public void findAll() { Account account = accountDao.read("中国"); System.out.println(account.getUsername()); System.out.println(account.getPassword()); } }
@Autowired自动注入注解标签。也可以通过@Resource(name="accountDao")来注入。