Spring注解之@Autowired

@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保留,因此可以通过反射读取;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值