持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第2天,点击查看活动详情
Spring中注解(重要)
使用注解装配对象到IOC
位置:在类的上面标识。
注意:
- Spring本身不区分四个注解【注解本质一样,都是Component】,目的是提高代码可读性。
- Java中的约定:约束(Maven包结构、Java命名规则等)>注解>XML>代码
- 关于beanid:不使用value,默认将类名首字母小写作为beanid。也可以使用value属性/省略value从而设置beanid。
-
装配对象的四个注解:
- @Component(组件):装配普通组件到IOC中。
- @Repository(仓库):装配持久化层到IOC中。
- @Service(业务):装配业务逻辑层到IOC中。
- @Controller(控制):装配控制层/表示层组件到IOC中。
-
使用注解装配对象的步骤:
-
使用组件扫描(目的是扫描到注解)
//注意命名空间。 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!--开启组件扫描 base-package:设置扫描注解包名【当前包及其子包】--> <context:component-scan base-package="Spring"></context:component-scan> </beans> -
使用注解标识组件(标识的是实现类Impl,因为只有实现类才可以创建对象)
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //使用Component注解 Dept dept = context.getBean("dept", Dept.class); System.out.println("dept = " + dept); //使用Repository注解 DeptDaoImpl deptdaoimpl = context.getBean("deptdaoimpl", DeptDaoImpl.class); System.out.println("deptdaoimpl = " + deptdaoimpl); //使用Service注解 DeptServiceImpl deptserviceimpl = context.getBean("deptserviceimpl", DeptServiceImpl.class); System.out.println("deptserviceimpl = " + deptserviceimpl); //使用Controller注解 DeptController deptController = context.getBean("deptController", DeptController.class); System.out.println("deptController = " + deptController);
-
使用注解管理对象之间的依赖关系
依赖关系:比如Service层依赖Dao层的对象。
使用 @Autowired注解来管理对象之间的依赖关系(装配对象中的属性)。
-
使用方式:直接注解到属性上。
-
装配原理:反射机制
-
装配方式
-
先按照byType进行匹配
-
匹配1个:匹配成功,正常使用
-
匹配0个:
-
默认【@Autowired(required=true)】报错
/*expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} */ -
@Autowired(required=false),不会报错
-
-
匹配多个
-
再按照byName进行唯一筛选
-
筛选成功【对象中属性名称==beanId】,正常使用
-
筛选失败【对象中属性名称!=beanId】,报如下错误:
//expected single matching bean but found 2: deptDao,deptDao2
-
-
-
-
-
@Autowired中required属性
- true:表示被标识的属性必须装配数值,如未装配,会报错。
- false:表示被标识的属性不必须装配数值,如未装配,不会报错。
-
@Qualifier注解
- 作用:配合@Autowired使用,可以设置装配属性的beanid,而不是必须与属性名相同。
- 注意:不能单独使用,需要与@Autowired一起使用。
-
@Value注解
- 作用:装配对象中的属性(针对字面量数值)
\