@Controller
@RequestMapping(value = "/project")
public class ProjectController {
@Autowired
private ProjectService projectService;
@PostMapping(value="/getProjectTableList")
@ResponseBody
public ResponseObj getProjectTableList(@RequestBody TableRequestObj<MpProjectSummary> t) throws Exception{
return projectService.getProjectTableList(t);
}
@Autowired
实现了bean的自动注入功能。在Spring Boot应用启动时,Spring容器会自动装载一个org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
处理器,当容器扫扫描到 @Autowired
注解时,会在IoC容器找到相应类型的Bean,并且实现注入。
@Autowired
默认属性 required=true,当不能确定Spring容器中一定拥有某个类的Bean时,可以在需要自动注入该类Bean的地方使用@Autowired(required=false)
,此时就算匹配不到Bean也不会抛出BeanCreationException
异常。
下面是@Autowired
注解源码:
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
/**
* Declares whether the annotated dependency is required.
* <p>Defaults to {@code true}.
*/
boolean required() default true;
}
其中,
@Target
决定@Autowired
注解可以加在哪些成分上。
ElementType.TYPE:表示注解可以用在类,接口(包括注解类型),或枚举声明上。
ElementType.FIELD:域声明上(包括枚举常量上)。
ElementType.METHOD:方法声明上。
ElementType.PARAMETER:参数声明上。
ElementType.CONSTRUCTOR:构造函数声明上。
ElementType.LOCAL_VARIABLE:本地变量上。
ElementType.ANNOTATION_TYPE:注解类型声明上。
ElementType.PACKAGE:包声明上。
@Retention
表示注解保留策略。@Retention
有一个RetentionPolicy
类型的属性value,来指定注解的生命周期(保留时间)。
RetentionPolicy.SOURCE:注解只保留在源文件,当Java文件编译成class文件的时候,注解会被编译器移除;
RetentionPolicy.CLASS:注解会被编译器记录在class文件中但在运行时会被VM移除,这也是默认的策略;
RetentionPolicy.RUNTIME:注解会被编译器记录在class文件中并且在运行时会被VM保留,因此可以通过反射读取;