Spring
学习方式:掌握用法、深入理解、不断实践、反复总结、再次深入理解与实践
网站:
http://projects.spring.io/spring-framework
简介:Spring是一个轻量级的控制反转和面向切面的容器
1、IOC:将Bean初始化加载到容器中。
Bean是如何加载到容器的?可以使用Spring注解,例如下面的注解:(被注解的Java类当做Bean实例,将Bean实例加载到容器里)
@Controller:标注一个控制器组件类
@Service:标注一个业务逻辑组件类
@Repository:标注一个DAO组件类
@Component :标准一个普通的spring Bean类
@Component可以代替@Repository、@Service、@Controller,因为这三个注解是被@Component标注的
@Component public class UserService
指定了某些类可作为Spring Bean类使用后,最好还需要让Spring搜索指定路径,在Spring配置文件加入如下配置:
<context:component-scan base-package=“org.springframework.*”/>
2、@Autowired主要用于注入某个接口。
@Autowired是Spring的注解,@Resource是javax.annotation注解,不是Spring的注解,一般很少使用;
@Autowired private UserService userService;
3、@RequestMapping:将url映射到某个处理类或者特定处理请求的方法。
如果不指定方法类型的话,可以使用 HTTP GET/POST 方法请求数据,@GetMapping、@PostMapping、@PutMapping、@DeleteMapping。
@RequestMapping(value="/user") public class UserController
4、@RequestParam :将请求的参数绑定到方法中的参数上,前端传递的参数为空时会报错,常用于设置默认值。
@RequestParam(required=false)用于关闭必须参数的限制;
添加defaultValue="value"来设置默认值;
@RequestMapping(value = "/findByPage1", method = RequestMethod.GET) public List<User> findByPage1(@RequestParam(defaultValue = "1") Integer size, @RequestParam(defaultValue = "3") Integer page)
@PathVariable:常和变量关联使用,设置定位符。
@RequestMapping(value = "/findByPage/{size}/{page}", method = RequestMethod.GET) public List<User> findByPage(@PathVariable Integer size, @PathVariable Integer page)
@RequestParam用于静态传参,@PathVariable用于动态传参;
如上面的
5、@RequestBody是将方法参数绑定到HTTP请求Body上。
$.ajax({ url:"/login", type:"POST", data:'{"userName":"admin","pwd","admin123"}', content-type:"application/json charset=utf-8", success:function(data){ alert("request success ! "); } });
@requestMapping("/login") public void login(@requestBody String userName,@requestBody String pwd){ System.out.println(userName+" :"+pwd); }
前端传递 J S O N 字符串时,需要使用该注解把字符串绑定到后台对应的实体类中 \color{#FF0000}{前端传递JSON字符串时,需要使用该注解把字符串绑定到后台对应的实体类中}前端传递JSON字符串时,需要使用该注解把字符串绑定到后台对应的实体类中,但必须保证属性名一样;
6、@ResponseBody在输出JSON格式的数据时,会经常用到,例如’{“userName”:“xxx”,“pwd”:“xxx”}'数据。
将返回的数据直接以JSON字符串的形式响应给前端。
7、@RestController注解相当于@ResponseBody + @Controller合在一起的作用,方法不用再添加@ResponseBody 注解,使用该注解时该方法无法返回jsp页面,而是返回json数据,所以在SSM一般很少使用,但是在SpringBoot项目中比较常见
8、@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
在处理dao层或service层的事务操作时,譬如删除失败时的回滚操作。使用**@Transactional** 作为注解,但是需要在配置文件激活
开启注解方式声明事务:
<tx:annotation-driven transaction-manager=“transactionManager” />
9、@JsonIgnore注解作用是json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响,一般标记在属性或者方法上,返回的json数据即不包含属性。
/** 开始时间 */ @JsonIgnore private String beginTime;