Home >Java >javaTutorial >Summary of annotations and simple application introduction in Spring
This article brings you a summary of annotations and a simple application introduction in Spring. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Identifies a class as a Spring MVC controller processor, used to create objects that handle http requests.
1@Controller 2public class TestController { 3 @RequestMapping("/test") 4 public String test(Map1384ae87b3aa4d7618d5d6d4b582a21b map){ 5 6 return "hello"; 7 } 8}
Annotations added after Spring 4. It turns out that returning json in @Controller requires @ResponseBody to cooperate. If you directly use @RestController to replace @Controller, you don’t need to configure @ResponseBody. By default, json format is returned.
1@RestController 2public class TestController { 3 @RequestMapping("/test") 4 public String test(Map1384ae87b3aa4d7618d5d6d4b582a21b map){ 5 6 return "hello"; 7 } 8}
is used to annotate business layer components. To put it bluntly, it means adding that you have an annotation to inject this class into the spring configuration
is used to assemble beans and can be written on fields or methods.
By default, the dependent object must exist. If you want to allow null values, you can set its required attribute to false, for example: @Autowired(required=false)
Class definition: Provide preliminary request mapping information, relative to the root directory of the WEB application.
Method: Provide further subdivision mapping information, relative to the URL at the class definition.
Students who have used RequestMapping know that it has many functions, so the detailed usage
I will talk about it in the next article. Please follow the public account so as not to miss it.
is used to map the request parameter area data to the parameters of the function processing method
For example
1public Resp test(@RequestParam Integer id){ 2 return Resp.success(customerInfoService.fetch(id)); 3 }
This id is to be received from the interface The value of the passed parameter id. If the parameter name passed by the interface is inconsistent with what you received, you can also use the following
1public Resp test(@RequestParam(value="course_id") Integer id){ 2 return Resp.success(customerInfoService.fetch(id)); 3 }
where course_id is the parameter passed by the interface, and id is the parameter name mapping course_id
There are three ways to use it:
1. Mark it on the method. The
mark on the method will be executed before each method marked with @RequestMapping. If there is a return value, the return value will be automatically added to the ModelMap.
A. On methods that return:
When ModelAttribute is set to value, the value returned by the method will use this value as the key, use the value received by the parameter as the value, and store it in the Model. After the following method is executed, it is ultimately equivalent to
model.addAttribute("user_name", name); If @ModelAttribute does not have a custom value, it is equivalent to
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. In the method that does not return Above:
Needs manual model.add method
1 @ModelAttribute 2 public void before(@RequestParam(required = false) Integer age, Model model) { 3 model.addAttribute("age", age); 4 System.out.println("进入了1:" + age); 5 }
We build a request method under the current class:
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 }
Enter the access address in the browser and add parameters:
http://localhost:8081/api/test/mod?name=I am Xiaocai&age=12
The final output is as follows:
1 entered 1:40
2 entered 2: I am Xiaocai
3 Enter mod
4 The value accepted by the parameter {name=I am Xiaocai;age=12}
5The value passed by model:{age=40, user_name=I am Xiaocai}
2. Mark on the parameters of the method.
Marked on the parameters of the method, the parameters passed by the client will be injected into the specified object by name, and this object will be automatically added to the ModelMap to facilitate the use of the View layer.
We are above Add a method to the class as follows
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 }
Enter the access address in the browser and add parameters:
http://localhost:8081/api/test/mod2?name=我是小菜&age= 12
Final output:
1进入了1:40 2进入了2:我是小菜 3进入mod2 4user_name:我是小菜 5name:我是小菜 6age:40 7model:{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}
It can be seen from the results that the @ModelAttribute annotation used in method parameters is actually a way to accept parameters and automatically put them into the Model object for ease of use.
is used to mark cached queries. Can be used in methods or classes.
When marked on a method, it means that the method supports caching.
When marked on a class, it means that all methods of the class support caching. of.
Parameter | Explanation | Example |
---|---|---|
value | Name | @Cacheable(value={”c1”,”c2”} |
key | key | @Cacheable(value=”c1”,key=”#id”) |
Condition | @Cacheable(value="c1", condition="#id=1") For example, @Cacheable(value="UserCache") identifies that when the method marked with this annotation is called, the logic is added from the cache by default The logic of obtaining results in the cache. If there is no data in the cache, the query logic written by the user will be executed. After the query is successful, the results will be put into the cache at the same time. When it comes to cache, it is in the form of key-value, so the key is in the method. The parameter (id), value is the result of the query, and the namespace UserCache is defined in spring*.xml. |
参数 | 解释 | 例子 |
---|---|---|
value | 名称 | @CachEvict(value={”c1”,”c2”} |
key | key | @CachEvict(value=”c1”,key=”#id”) |
condition | 缓存的条件,可以为空 | |
allEntries | 是否清空所有缓存内容 | @CachEvict(value=”c1”,allEntries=true) |
beforeInvocation | 是否在方法执行前就清空 | @CachEvict(value=”c1”,beforeInvocation=true) |
@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方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;
用来标记是在项目启动的时候执行这个方法。用来修饰一个非静态的void()方法
也就是spring容器启动时就执行,多用于一些全局配置、数据字典之类的加载
被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。PreDestroy()方法在destroy()方法执行执行之后执
被@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前
用于标注数据访问组件,即DAO组件
泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注
用来配置 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实例。
默认情况下Spring MVC将模型中的数据存储到request域中。当一个请求结束后,数据就失效了。如果要跨页面使用。那么需要使用到session。而@SessionAttributes注解就可以使得模型中的数据存储一份到session域中
参数:
names:这是一个字符串数组。里面应写需要存储到session中数据的名称。
types:根据指定参数的类型,将模型中对应类型的参数存储到session中
value:和names是一样的。
1@Controller 2@SessionAttributes(value={"names"},types={Integer.class}) 3public class ScopeService { 4 @RequestMapping("/testSession") 5 public String test(Map1384ae87b3aa4d7618d5d6d4b582a21b map){ 6 map.put("names", Arrays.asList("a","b","c")); 7 map.put("age", 12); 8 return "hello"; 9 } 10}
适用于bean属性setter方法,并表示受影响的bean属性必须在XML配置文件在配置时进行填充。否则,容器会抛出一个BeanInitializationException异常。
当你创建多个具有相同类型的 bean 时,并且想要用一个属性只为它们其中的一个进行装配,在这种情况下,你可以使用 @Qualifier 注释和 @Autowired 注释通过指定哪一个真正的 bean 将会被装配来消除混乱。
The above is the detailed content of Summary of annotations and simple application introduction in Spring. For more information, please follow other related articles on the PHP Chinese website!