Common Spring Framework Annotations and Their Usage
This article explains the purpose and usage of frequently used Spring annotations such as @Controller, @RestController, @Service, @Autowired, @RequestMapping, @RequestParam, @ModelAttribute, @Cacheable, @CacheEvict, @Resource, @PostConstruct, @PreDestroy, @Repository, @Component, @Scope, @SessionAttributes, and @Qualifier, providing code examples and practical notes for Java backend development.
@Controller
Marks a class as a Spring MVC controller handler for processing HTTP requests.
@Controller
public class TestController {
@RequestMapping("/test")
public String test(Map<String,Object> map){
return "hello";
}
}@RestController
Introduced after Spring 4, it combines @Controller and @ResponseBody, so methods return JSON by default without needing @ResponseBody.
@RestController
public class TestController {
@RequestMapping("/test")
public String test(Map<String,Object> map){
return "hello";
}
}@Service
Indicates a service layer component, allowing the class to be injected into Spring configuration via annotation.
@Autowired
Injects a bean into a field or method. By default the dependency must exist; set required=false to allow null values.
@RequestMapping
At the class level it provides a base URL mapping relative to the web application's root; at the method level it defines a more specific mapping relative to the class mapping.
@RequestParam
Maps request parameters to method arguments. Example:
public Resp test(@RequestParam Integer id){
return Resp.success(customerInfoService.fetch(id));
}If the request parameter name differs from the method argument name, specify the name explicitly:
public Resp test(@RequestParam(value="course_id") Integer id){
return Resp.success(customerInfoService.fetch(id));
}@ModelAttribute
Can be placed on a method or a method parameter. When placed on a method, its return value is added to the model before each @RequestMapping method executes. When placed on a parameter, the argument is populated from request data and added to the model automatically.
@ModelAttribute(value="user_name")
public String before2(@RequestParam(required=false) String name, Model model){
System.out.println("进入了2:" + name);
return name;
} @ModelAttribute
public void before(@RequestParam(required=false) Integer age, Model model){
model.addAttribute("age", age);
System.out.println("进入了1:" + age);
}@Cacheable
Marks a method (or class) as cacheable. When invoked, the result is first looked up in the specified cache; if absent, the method executes and the result is stored in the cache.
Parameter
Description
Example
value
Cache name
@Cacheable(value={"c1","c2"})
key
Cache key
@Cacheable(value="c1",key="#id")
condition
Condition expression
@Cacheable(value="c1",condition="#id==1")
@Cacheable(value="UserCache")
public int getUserAge(int id){
int age = getUser(id);
return age;
}@CacheEvict
Marks a method that clears cache entries when invoked.
Parameter
Description
Example
value
Cache name
@CacheEvict(value={"c1","c2"})
key
Cache key
@CacheEvict(value="c1",key="#id")
allEntries
Whether to clear all entries
@CacheEvict(value="c1",allEntries=true)
beforeInvocation
Whether to clear before method execution
@CacheEvict(value="c1",beforeInvocation=true)
@Resource
Functions similarly to @Autowired but defaults to injection by name. It has name and type attributes to control the injection strategy.
@PostConstruct
Marks a non‑static void method to be executed after the bean is constructed and dependencies are injected, typically used for initialization tasks.
@PreDestroy
Marks a method to be executed before the bean is destroyed, useful for cleanup operations.
@Repository
Designates a data access component (DAO) in the persistence layer.
@Component
A generic stereotype for any Spring-managed component that does not fit other specific stereotypes.
@Scope
Specifies the bean scope: singleton, prototype, request, session, or globalSession.
@SessionAttributes
Stores model attributes in the HTTP session to make them available across multiple requests.
@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";
}
}@Required
Applied to bean property setter methods, indicating that the property must be configured in XML; otherwise a BeanInitializationException is thrown.
@Qualifier
Used together with @Autowired to disambiguate which bean should be injected when multiple candidates of the same type exist.
PS: If you find this sharing useful, feel free to like and share.
(End)
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
