使用注解须知:
1. 导入约束:context约束
2. 配置注解的支持:context:annotation-config
- "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
- https://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context
- https://www.springframework.org/schema/context/spring-context.xsd">
-
- <context:annotation-config/>
-
- beans>
@Autowired
直接在属性上使用即可,也可以在set方式上使用
使用Autowired时,可以不用编写set方法,前提是自动装配的属性在ioc(Spring)容器中存在,且符合名字byname!
测试代码:
- public class People {
-
- // 如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
- @Autowired(required = false)
- private Cat cat;
- @Autowired
- private Dog dog;
- private String name;
- }
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value="xxx")去配合@Autowired的使用,指定一个唯一的bean对象注入。
- public class People {
-
- // 如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
- @Autowired(required = false)
- @Qualifier(value = "cat111")
- private Cat cat;
-
- @Autowired
- @Qualifier(value = "dog222")
- private Dog dog;
- private String name;