原文地址:spring注解学习之一
作者:懂的Me
近日闲来无事,趁这空儿学点东西。领导建议我们学习一下spring注解,以备将来之需。从网上找了一些资料,边学边总结下,哪里不对,还请各位指点哈。开始喽!
@Resource 与@Autowired功能一样,是JSR-250标准注解,用来替换spring专有注解
@Autowired
@RequestMapping(method=RequestMethod.GET) 用来指明请求的方式是get
注解
@Component,共有4种“组件”式注解:
先看一段代码吧:
- @Controller
① - @RequestMapping("/account.do")
② - public
class AccountController { -
-
@Autowired ③ -
private AccountService accountService; -
-
@RequestMapping(method = RequestMethod.GET) ④ -
public void hello(HttpServletRequest request, HttpServletResponse response) -
throws Exception { -
-
String username = ServletRequestUtils.getRequiredStringParamet er( -
request, "username"); -
String password = ServletRequestUtils.getRequiredStringParamet er( -
request, "password"); -
System.out.println(accountService.verify(username, password)); -
} - }
下面对以上代码标有序号的做一简单的解释:
1、
@contorller 告诉spring这段代码是一个控制器
2、
@RequestMapping("/account.do") 定义访问这个控制器的请求路径是“account.do”
3、@Autowired 声明变量 自动织入了业务层AccountService,可省去set方法
4、@RequestMapping(params=“method=hello”) 指明访问当前控制器中某方法的请求路径
如:“/account.do?method=hello”
以上是控制器的代码,下面来看一下service
- public
interface AccountService { -
-
-
boolean verify(String username, String password); -
- }
spring的接口不需要任何注解,它只是一个简单的接口
重要的是实现层
- 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; -
- @Service
① - @Transactional
② - public
class AccountServiceImpl implements AccountService { -
-
@Autowired -
private AccountDao accountDao; -
-
@Override -
public boolean verify(String username, String password) { -
-
Account account = accountDao.read(username); -
-
if (password.equals(account.getPassword())) { -
return true; -
} else { -
return false; -
} -
} -
- }
1、注解@Service用于标识这是一个Service层实现
2、 @Transctational 用于控制事务,将事务控制在业务层是比较实务的做法
持久层:AccountDao和AccountDaoImpl类
- public
interface AccountDao { -
-
-
Account read(String username); -
- }
接口,无需注解。
- import
org.springframework.stereotype.Repository; - import
org.zlex.spring.dao.AccountDao; - import
org.zlex.spring.domain.Account; -
- @Repository
① - public
class AccountDaoImpl implements AccountDao { -
-
@Override -
public Account read(String username) { -
-
return new Account(username,"wolf"); -
} -
- }
① @Repository 持久层的标识
这样spring容器就完成了控制层、业务层和持久层的构建。
启动服务访问:http://localhost:8080/spring/account.do?method=hello&username=sunsan&password=wolf即可访问。当控制台打印出true时,说明构建成功。
补:
@Component:可装载组件
@Repository:持久层组件
@Service:服务层组件
@Controller:控制层组件
@Repository:持久层组件
@Service:服务层组件
@Controller:控制层组件