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层