本文转自 snowolf的博客组:spring注解学习手札
这是一组从spring搭建到注解详细使用的学习过程的博文组,一共八篇博文。
1、@RequestMapping("/requestName")注解类和方法,指定请求路径,@RequestMapping(method = RequestMethod.GET)(处理get请求)
2、替代写xml bean将配置bean的注解:@Controller(控制层)、@Service(业务逻辑层)、@Repository(数据持久层)、@Component(通用组件)
3、@autowired(自动注入),@resource(name="lattice")(按指定beanName注入,需要获取自定义对象名时指定beanName)
4、由JSR-250规范定义的注解:@Resource、@PostConstruct(在方法上加上注解@PostConstruct,这个方法就会在Bean初始化之后被Spring容器执行)以及@PreDestroy。
5、@Transactional(用于控制事务,将事务定位在业务层);@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)(用于配置@Transactional事务)
6、@Value获取配置文件内容@Value("/WEB-INF/database.properties")、@Value("${jdbc.url}");@ImportResource("/WEB-INF/database.properties") (如果只有这么一个类使用该配置文件: )
7、public void hello(@RequestParam("username") String username)(按照前台提交数据name属性指定接收参数)
8、@SessionAttributes("msg")(在返回值为请求方法返回值map类型时,指定配置到sessionScope作用域中的数据的kayName)
9、@InitBinder(注解对象为方法,表示在进入请求类后,进去请求方法之前执行的方法,一般用于处理时间格式数据,用于表单自定义属性绑定)
10、@ContextConfiguration(locations = "classpath:applicationContext.xml")(导入配置文件,一般用于修饰单独测试类)
11、@RequestBody(HTTP请求正文转换为适合的HttpMessageConverter对象,HttpMessageConverter接口,需要开启
12、@ResponseBody (将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流,我在使用ajax请求从后台拿数据时用过,将我的返回值list
13、@ExceptionHandler(RuntimeException.class)(拦截RuntimeException)
@Autowired
private AccountService accountService; //这个对象名一定是类名首字母小写的命名
//在类中获取配置文件的值
@Value("${jdbc.url}")
private String url;
ModelAndView
Model
View
Map
String
null
@InitBinder
public void initBinder(WebDataBinder binder) {
// 忽略字段绑定异常
// binder.setIgnoreInvalidFields(true);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, "birthday",
new CustomDateEditor(format, true));
}
@ResponseBody
@RequestMapping("/lattice")
public List testLattice(@RequestParam("name")String name,@RequestParam("age")int age){
System.out.println(name+"\t"+age);
try {
List list;
list = studentService.getAllStudentList();
if(list!=null){
for(int i=0;i
@RequestMapping(value = "/person/profile/{id}", method = RequestMethod.GET)
public @ResponseBody
//GET模式下,这里使用了@PathVariable绑定输入参数
Person porfile(@PathVariable("id") int uid) {
return new Person(uid, name, status);
}
@Controller
public class AccessController {
/**
* 异常页面控制
*
* @param runtimeException
* @return
*/
@ExceptionHandler(RuntimeException.class)
public String runtimeExceptionHandler(RuntimeException runtimeException,
ModelMap modelMap) {
logger.error(runtimeException.getLocalizedMessage());
modelMap.put("status", IntegralConstant.FAIL_STATUS);
return "exception";
}
}