前言

用过spring的人都晓得,spring简略的通过注解就能够实现很多事件,但这些货色是如何实现的呢以及如何利用到咱们本人的代码中?接下来,让咱们一起开启注解的旅程。

1. @Controller

标识一个该类是Spring MVC controller处理器,用来创立解决http申请的对象.

@Controllerpublic class TestController {        @RequestMapping("/test")        public String test(Map<String,Object> map){            return "hello";        }}

2. @Component、@Repository、@Service、@Controller作用等价雷同的

区别:如果 Web 应用程序采纳了经典的三层分层构造的话,最好在长久层、业务层和管制层别离采纳 @Repository、@Service 和 @Controller 对分层中的类进行正文,而用 @Component 对那些比拟中立的类进行正文。

用来拆卸bean,次要用于标注业务层组件,通过注解的形式将该类退出到spring 中进行治理。

@Servicepublic interface UserService {   User login(String username,String password); }//当把注解写在接口上时,spring容器会注入失败。//注解写在类上  注入不会失败。@Servicepublic class UserServiceImpl  implements UserService{       @Autowired       private  UserMapper userMapper;}@Controller@RequestMapping("user")public class UserController {    @Autowired    private UserService userService}

3. @Autowired

用来拆卸bean,能够写在字段上,也能够写在办法上。
默认状况下必须要求依赖对象必须存在,如果要容许null值,能够设置它的required属性为false,例如:@Autowired(required=false)

4. @RequestMapping

类定义处:提供初步的申请映射信息,绝对于 WEB 利用的根目录。
办法处:提供进一步的细分映射信息,绝对于类定义处的 URL。
说白了,就是例如(“user”)网站上拜访localhost:8080/user.html就能够拜访这个办法和html页面。

5. @RequestParam

用于将申请参数区数据映射到性能解决办法的参数上
例如:

public Resp test(@RequestParam Integer id){        return Resp.success(customerInfoService.fetch(id));}

这个id就是要接管从接口传递过去的参数id的值的,如果接口传递过去的参数名和你接管的不统一,也能够如下:

public Resp test(@RequestParam(value="userId") Integer id){    return Resp.success(customerInfoService.fetch(id));}

其中userId就是接口传递的参数,id就是映射userId的参数名。

6. @ModelAttribute

应用中央有三种:

  1. 标记在办法上。

标记在办法上,会在每一个@RequestMapping标注的办法前执行,如果有返回值,则主动>将该返回值退出到ModelMap中。

A.在有返回的办法上:
当ModelAttribute设置了value,办法返回的值会以这个value为key,以参数承受到的值作为value,存入到Model中,如上面的办法执行之后,最终相当于 model.addAttribute(“user_name”, name);如果 @ModelAttribute没有自定义value,则相当于
model.addAttribute(“name”, name);

1@ModelAttribute(value="user_name")2    public String before2(@RequestParam(required = false) String name, Model model) {3        System.out.println("进入了2:" + name);4        return name;5    }

B.在没返回的办法上:
须要手动model.add办法

1    @ModelAttribute2    public void before(@RequestParam(required = false) Integer age, Model model) {3        model.addAttribute("age", age);4        System.out.println("进入了1:" + age);5    }

咱们在以后类下建一个申请办法:

 1@RequestMapping(value="/mod") 2    public Resp mod( 3            @RequestParam(required = false) String name, 4            @RequestParam(required = false) Integer age,  5            Model model){ 6        System.out.println("进入mod"); 7        System.out.println("参数承受的数值{name="+name+";age="+age+"}"); 8        System.out.println("model传过来的值:"+model); 9        return Resp.success("1");10    }

在浏览器中输出拜访地址并且加上参数:
http://localhost:8081/api/test/mod?name=我是小菜&age=12

最终输入如下:

1进入了1:402进入了2:我是小菜3进入mod4参数承受的数值{name=我是小菜;age=12}5model传过来的值:{age=40, user_name=我是小菜}
  1. 标记在办法的参数上。

标记在办法的参数上,会将客户端传递过去的参数按名称注入到指定对象中,并且会将这个对象主动退出ModelMap中,便于View层应用.
咱们在下面的类中退出一个办法如下

 1@RequestMapping(value="/mod2") 2    public Resp mod2(@ModelAttribute("user_name") String user_name,  3            @ModelAttribute("name") String name, 4            @ModelAttribute("age") Integer age,Model model){ 5        System.out.println("进入mod2"); 6        System.out.println("user_name:"+user_name); 7        System.out.println("name:"+name); 8        System.out.println("age:"+age); 9        System.out.println("model:"+model);10        return Resp.success("1");11    }

在浏览器中输出拜访地址并且加上参数:
http://localhost:8081/api/test/mod2?name=我是小菜&age=12
最终输入:

1进入了1:402进入了2:我是小菜3进入mod24user_name:我是小菜5name:我是小菜6age:407model:{user_name=我是小菜, 

org.springframework.validation.BindingResult.user_name=org.springframework.validation.BeanPropertyBindingResult: 0 errors, name=我是小菜, org.springframework.validation.BindingResult.name=org.springframework.validation.BeanPropertyBindingResult: 0 errors, age=40, org.springframework.validation.BindingResult.age=org.springframework.validation.BeanPropertyBindingResult: 0 errors}
从后果就能看出,用在办法参数中的@ModelAttribute注解,实际上是一种承受参数并且主动放入Model对象中,便于应用。

7. @Cacheable

用来标记缓存查问。可用用于办法或者类中,
当标记在一个办法上时示意该办法是反对缓存的,
当标记在一个类上时则示意该类所有的办法都是反对缓存的。
参数列表

@Cacheable(value="UserCache")// 应用了一个缓存名叫 accountCache   public Account getUserAge(int id) {       //这里不必写缓存的逻辑,间接按失常业务逻辑走即可,     //缓存通过切面主动切入      int age=getUser(id);        return age;   } 

8. @CacheEvict

用来标记要清空缓存的办法,当这个办法被调用后,即会清空缓存。 @CacheEvict(value=”UserCache”)
参数列表

9. @Resource

@Resource的作用相当于@Autowired
只不过@Autowired按byType主动注入,
而@Resource默认按 byName主动注入罢了。

@Resource有两个属性是比拟重要的,分是name和type,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果应用name属性,则应用byName的主动注入策略,而应用type属性时则应用byType主动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制应用byName主动注入策略。

@Resource拆卸程序:
如果同时指定了name和type,则从Spring上下文中找到惟一匹配的bean进行拆卸,找不到则抛出异样
如果指定了name,则从上下文中查找名称(id)匹配的bean进行拆卸,找不到则抛出异样

如果指定了type,则从上下文中找到类型匹配的惟一bean进行拆卸,找不到或者找到多个,都会抛出异样

如果既没有指定name,又没有指定type,则主动依照byName形式进行拆卸;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则主动拆卸;

10. @PostConstruct

用来标记是在我的项目启动的时候执行这个办法。用来润饰一个非动态的void()办法也就是spring容器启动时就执行,多用于一些全局配置、数据字典之类的加载

被@PostConstruct润饰的办法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()办法之前执行。PreDestroy()办法在destroy()办法执行执行之后执

11. @PreDestroy

被@PreDestroy润饰的办法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,相似于Servlet的destroy()办法。被@PreDestroy润饰的办法会在destroy()办法之后运行,在Servlet被彻底卸载之前

12.@Repository

用于标注数据拜访组件,即DAO组件

13.@Component

泛指组件,当组件不好归类的时候,咱们能够应用这个注解进行标注

14.@Scope

用来配置 spring bean 的作用域,它标识 bean 的作用域。
默认值是单例

**singleton:单例模式,全局有且仅有一个实例
prototype:原型模式,每次获取Bean的时候会有一个新的实例

request:request示意该针对每一次HTTP申请都会产生一个新的bean,同时该bean仅在以后HTTP request内无效

session:session作用域示意该针对每一次HTTP申请都会产生一个新的bean,同时该bean仅在以后HTTP session内无效

global session:只在portal利用中有用,给每一个 global http session 新建一个Bean实例。**

15. @SessionAttributes

默认状况下Spring MVC将模型中的数据存储到request域中。当一个申请完结后,数据就生效了。如果要跨页面应用。那么须要应用到session。而@SessionAttributes注解就能够使得模型中的数据存储一份到session域中

参数:
names:这是一个字符串数组。外面应写须要存储到session中数据的名称。
types:依据指定参数的类型,将模型中对应类型的参数存储到session中
value:和names是一样的。

 @Controller @SessionAttributes(value={"names"},types={Integer.class}) public class ScopeService {         @RequestMapping("/testSession")         public String test(Map<String,Object> map){             map.put("names", Arrays.asList("a","b","c"));             map.put("age", 12);             return "hello";         }}

16. @Required

实用于bean属性setter办法,并示意受影响的bean属性必须在XML配置文件在配置时进行填充。否则,容器会抛出一个BeanInitializationException异样。

17. @Qualifier

当你创立多个具备雷同类型的 bean 时,并且想要用一个属性只为它们其中的一个进行拆卸,在这种状况下,你能够应用 @Qualifier 正文和 @Autowired 正文通过指定哪一个真正的 bean 将会被拆卸来打消凌乱。

18.@PathVariable

@PathVariable能够用来映射URL中的占位符到指标办法的参数中

@RequestMapping("/testPathVariable/{id}")public String testPathVariable(@PathVariable("id") Integer id){    System.out.println("testPathVariable:"+id);    return SUCCESS;}

最初解释一下ajax相干注解:
Ajax相干注解
1.@RestController:定义的控制器所有办法默认返回的都是 @ResponseBody
的办法, 都会将返回值转换为JSON。留神:@RestController=@Controller+@ResponseBody

2.@ResponseBody:设置了 @ResponseBody 当前如果控制器办法返回了Java Bean 对象
则这个JavaBean会被转换为 JSON 对象, 放到响应的注释中发送浏览器
而且响应的 ContentType是 application/json, 示意JSON类型数据
3.@GetMapping:专门解决get类型申请
4.@PostMapping:专门解决post类型申请

注:@GetMapping("/get_test") 和 @RequestMapping(value = “/get_test”,method = RequestMethod.GET)等价的就是为了简化 RequestMapper 专门用于解决Get申请
图解:

19.@Data

类名后面增加@Data注解,lombok(插件,能够节俭实体类代码)会在类的编译期间为类增加getter,setter,toString办法。增加全属性笔记equals、hashCode办法。(说白了就是节俭实体类的代码,不必再写get、set。。。。。等办法)

测试之后,lombok的确主动生成了以上的一些办法。

最初

感激你看到这里,看完有什么的不懂的能够在评论区问我,感觉文章对你有帮忙的话记得给我点个赞,每天都会分享java相干技术文章或行业资讯,欢送大家关注和转发文章!