spring的注解
spring的主要的注解包括:{@Controller,@Service,@Repository,@RequestMapping,@ResponseBody, @Autowired,@Component
@Aspect,@Pointcut,@Around,@ModelAttribute}
1.@Controller 注入控制器(控制层)
2.@Service 注入服务对象 (业务层)
3.@Repository 注入dao对象(持久层)
4,@ModelAttribute 在controller调用前执行注解下的方法
使用这三个注解来注解类,需要把注解类纳入spring容器中进行管理。使用component扫描组件<context:component-scan base-package="com.toutiao" />
这是web应用程序使用的经典的三层框架,下面是详细代码。
1.controller层
@Controller() @RequestMapping("/user") public class UserController { @Autowired @Qualifier("userService") private UserService userService; @RequestMapping(value="/login") public String getUser(User user){ if (user.getPassword()==null && user.getName()==null) { return "login.jsp"; } User u = null; try { u = userService.query(user.getName(), user.getPassword()); } catch (Exception e) { e.printStackTrace(); } if (u == null) { return "login.jsp"; } return "home.jsp"; } }
2.Service层
@Service("userService") public class UserServiceImpl implements UserService{ @Autowired @Qualifier("userMapper") private UserMapper userMapper; @Override public User query(String name, String password) throws Exception { return userMapper.query(name, password); } }
3.Dao层
@Repository("userDao") public class UserDaoImpl implements UserDao { @Autowired(required=true) @Qualifier("commonDao") public ICommonDao commonDao; @Override public User query(String username, String pwd) throws Exception { String sql = "select * from user where username=? and password=?"; List<User> list = commonDao.queryBySql(User.class, sql, new Object[]{username,pwd}); if (list.size()>0) { return list.get(0); } return null; } }
要使用注解功能需要在xml中配置扫描器,如下第一行。第二行是配置aop。
<context:component-scan base-package="com.pandaw" /> <aop:aspectj-autoproxy/>
相关推荐
与卿画眉共浮生 2020-11-13
smalllove 2020-11-03
hellowordmonkey 2020-11-02
丽丽 2020-10-30
周太郎 2020-10-28
greensomnuss 2020-10-27
职业炮灰 2020-10-16
与卿画眉共浮生 2020-10-14
feinifi 2020-10-14
feinifi 2020-10-13
yangjinpingc 2020-10-09
davis 2020-09-29
RickyIT 2020-09-27
lisongchuang 2020-09-27
tangxiong0 2020-09-03
meleto 2020-08-17
幸运小侯子 2020-08-14
YangHuiLiang 2020-08-06