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/>