/** * 2010-1-23 */ package org.zlex.spring.service; /** * * @author <a href="mailto:[email protected]">梁栋</a> * @version 1.0 * @since 1.0 */ public interface AccountService { /** * 验证用户身份 * * @param username * @param password * @return */ boolean verify(String username, String password); }
接口不需要任何Spring注解相关的东西,它就是一个简单的接口!
重要的部分在于实现层,如下所示:
AccountServiceImpl.java
/** * 2010-1-23 */ package org.zlex.spring.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.zlex.spring.dao.AccountDao; import org.zlex.spring.domain.Account; import org.zlex.spring.service.AccountService; /** * * @author <a href="mailto:[email protected]">梁栋</a> * @version 1.0 * @since 1.0 */ @Service @Transactional public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; /* * (non-Javadoc) * * @see org.zlex.spring.service.AccountService#verify(java.lang.String, * java.lang.String) */ @Override public boolean verify(String username, String password) { Account account = accountDao.read(username); if (password.equals(account.getPassword())) { return true; } else { return false; } } }
注意以下内容:
@Service @Transactional
注解@Service用于标识这是一个Service层实现,@Transactional用于控制事务,将事务定位在业务层,这是非常务实的做法!
接下来,我们来看持久层:AccountDao和AccountDaoImpl类
AccountDao.java
/** * 2010-1-23 */ package org.zlex.spring.dao; import org.zlex.spring.domain.Account; /** * * @author <a href="mailto:[email protected]">梁栋</a> * @version 1.0 * @since 1.0 */ public interface AccountDao { /** * 读取用户信息 * * @param username * @return */ Account read(String username); }
这个接口就是简单的数据提取,无需任何Spring注解有关的东西!
再看其实现类:
AccountDaoImpl.java
/** * 2010-1-23 */ package org.zlex.spring.dao.impl; import org.springframework.stereotype.Repository; import org.zlex.spring.dao.AccountDao; import org.zlex.spring.domain.Account; /** * * @author <a href="mailto:[email protected]">梁栋</a> * @version 1.0 * @since 1.0 */ @Repository public class AccountDaoImpl implements AccountDao { /* (non-Javadoc) * @see org.zlex.spring.dao.AccountDao#read(java.lang.String) */ @Override public Account read(String username) { return new Account(username,"wolf"); } }
这里只需要注意注解:
@Repository
意为持久层,Dao实现这层我没有过于细致的介绍通过注解调用ORM或是JDBC来完成实现,这些内容后续细述!
这里我们没有提到注解@Component,共有4种“组件”式注解:
这样spring容器就完成了控制层、业务层和持久层的构建。
启动应用,访问http://localhost:8080/spring/account.do?username=snow&password=wolf
观察控制台,如果得到包含“true”的输出,本次构建就成功了!