使用注解配置需:
- 导入约束
<context:component-scan base-package="com.qian.test1"/>
- 配置注解的支持
<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">
@Autowired(required=true/false)
注解对象实现自动装配(if参数类型只有一个,byType,else,byName),无需像上文那样手写autowire="xxx"(并可省略set方法)
若显式定义required=true,则该对象可以为null,默认为false
@Autowired
private String name;
@Autowired(required=true)
private HammerBobby hb;
@Nullable
注解字段可以为null
@Qualifier(value="id名")
注解字段指定id名注入
@Component
注释类,等价于创建一个该类bean对象,可以直接getBean获取
@Value("属性值")
注释字段直接给值