spring注解详解

本文转自 snowolf的博客组:spring注解学习手札

这是一组从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接口,需要开启<mvc:annotation-driven  />

12、@ResponseBody (将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流,我在使用ajax请求从后台拿数据时用过,将我的返回值list<StudentEntity>转化成json数组的ajax回调data

13、@ExceptionHandler(RuntimeException.class)(拦截RuntimeException)

二、以上注解选择性代码展示

1、@autowired

@Autowired  
private AccountService accountService;  //这个对象名一定是类名首字母小写的命名

2、@Value获取配置文件的配置项:

<!-- 在xml文件中加载配置文件 -->
<util:properties id="jdbc" location="/WEB-INF/database.properties"/>  

//在类中获取配置文件的值
@Value("${jdbc.url}")   
private String url;  


3、spring请求方法可用返回值类型

ModelAndView 
Model 
View 
Map 
String 
null 

4、@initbinder

 @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));  
    }  

5、@ResponseBody:以下示例是一个通过Ajax访问的请求从后台获取数据

@ResponseBody
	@RequestMapping("/lattice")
	public List<StudentEntity> testLattice(@RequestParam("name")String name,@RequestParam("age")int age){
		System.out.println(name+"\t"+age);
		
		try {
			List<StudentEntity> list;
			list = studentService.getAllStudentList();
			if(list!=null){
				for(int i=0;i<list.size();i++){
					System.out.println(list.get(i).getS_name());
				}
			}
			return list;
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	} 
@RequestMapping(value = "/person/profile/{id}", method = RequestMethod.GET)  
public @ResponseBody 
//GET模式下,这里使用了@PathVariable绑定输入参数 
Person porfile(@PathVariable("id") int uid) {  
    return new Person(uid, name, status);  
}  

6、@exceptionHandler

@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";  
    }  
}  









  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值