Springboot常用注解(复习用)
起动和配置
@SpringbootApplication:标志该类为主启动类
=@EnableAutoConfiguration(启动Springboot的自动配置)+@ComponentScan(扫描该类所在包下所有被@Component (@Service,@Controller)标记的bean)+@Configuration(表明是一个配置类)
自动装配
@Autowired:根据类型自动装配,会在容器中寻找类型相同的bean注入
@Resource:根据名字自动装配
@Qualifier:与@Autowired一起使用(不能单独使用),根据名字装配
注册Bean
@Component:通用,标记该类为一个Bean
@Repository:标记Dao层的该类为一个Bean
@Service:标记服务层的该类为一个Bean
@Controller:标记该类为一个Controller
@RestController:标记该类所有方法不返回视图而是返回json数据
@Bean:表明方法的返回结果为一个Bean,Bean的id就是方法名
地址
@RequestMapping(value=" "):绑定的url地址
@GetMapping(value=" "):限定为get方法
@PostMapping(value=" "):限定为Post方法
传参
@PathVariable(" "):声明一个路径变量
eg:
@GetMapping("/user/{id}")
public User getUser(@PathVariable("id") Integer id)
@RequestParam(value=" ", required="true/false",defaultValue=" "):
将前端传过来的参数绑定到方法中(实际上不用加也可以,主要是可以用来实现一些特殊功能) required="true"表明请求中必须包含该参数,defaultValue表明不传参时的默认值
@GetMapping("/user/{id}")
public User getUser(@RequestParam(value="id",required=false,defaultValue="1") Integer id)
@RequestBody:接受前端传过来的json参数(必须是post方法?),并可以把这个json注入到一个对象中,一个request中只能有一个requestbody
@GetMapping("/user/{id}")
public User getUser(@RequestBody User user)
其他
@ConfiguratiomProperties:
将application配置文件中配置的每一个属性的值,映射到这个组件中;告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;参数 prefix = “person” : 将配置文件中的person下面的所有属性一一对应
/*
@ConfigurationProperties作用:
将application配置文件中配置的每一个属性的值,映射到这个组件中;
告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定
参数 prefix = “person” : 将配置文件中的person下面的所有属性一一对应
*/
@Component //注册bean
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
@Validated:参数校验,详见JSR303
@ResponseBody:作用在方法上表明该方法返回json字符串
@Scope(value=""):写在类前,表明类的作用域,四种常见的:singleton表明bean为单例模式(默认),prototype表明每次请求都会创建一个新的Bean,request表明每次请求都会创建一个新的Bean,且该Bean只在这个request内有效,session表明每次请求都会创建一个新的Bean且该Bean只在这个session内有效

浙公网安备 33010602011771号