spring注解注入

1、注解环境搭配

1.1 引入配置文件

首先配置文件需要先导入相应的aop和context约束以及配置注解的支持<context:annotation-config />

还需要导入<context:component-scan base-package="domain"/>扫描指定包下的组件,导入这个配置之后,就已经包含导入<context:annotation-config />这个配置了。所以实则只需要配置扫描包就行(可以看源码注释有说明到)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />
    <context:component-scan base-package="domain"/>
</beans>

1.2 需要导入aop的包

2、注解解释

2.1 注解@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;

}
  • 里面有required方法,默认为true,表示如果属性标记了这个注解,而这个属性没有在容器中,那么就会报错。也就是说不允许标记这个注解的属性或类在容器中不存在!!
  • @Autowired默认是按照类型(byType)注入的,如果多个Bean类型相同就会按照名字注入。如果通过类型和名字都匹配不到,可以使用注解@qualifier配合@Autowired使用,指定唯一的bean对象注入。

2.2 注解@Resource

和@Autowired作用是差不多的,都是用来自动装配的。默认按名字注入,多个名字相同则通过类型匹配。

2.3 注解@Nulable

字段标记了这个注解,说明这个字段可以为mull,可以用在构造方法,或者有参方法的参数里面。

2.4 注解@Component

作用:将某个类注入到spring容器中,将配bean

@Component
public class Dog {
}

相当于

<bean id="dog" class="domain.Dog"></bean>

 @Component有下面几个注解的衍生用于在web开发时区分mvc三层架构

  • @Repository    -- dao层
  • @Service         -- service层
  • @Controller     -- controller层

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值