一、开启注解支持
在spring配置文件appContextAnnotat.xml中,开启注解驱动支持,即加上<context:annotation-config/>
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
</beans>
二、@Autowired
@Autowired(required=true)
构造器、字段、方法
此注解是使bean自动装配,代替xml的自动装配。
@Autowired根据参数类型(ByType)自动装配,如果有多个同个类型的bean,根据名称装配(spring3.3.1是这样的,我在网上找了很多资料,都没有提到这个,不知是否与版本相关)。
@Autowired(required = false) ,这等于告诉 Spring:在找不到匹配 Bean 时也不报错。@Autowired(required = false) 会很少用到
1.在Bean的字段上添加@AutoWired注解:
public class DaoImpl implements IDao{
@Autowired
private Student student;
// 得到学生的信息
@Override
public String getStuInfo() {
return "id:"+student.getId() + " name:" + student.getName();
}
//可不写set、get,因其用字段注入,不是从set方法注入
}
2.在appContextAnnotat.xml配置文件中加Student Bean和DaoImpl Bean
<bean id="student" class="com.spring.annotation.Student">
<property name="id" value="123456"/>
<property name="name" value="zhangsan"/>
</bean>
<bean id="dao" class="com.spring.annotation.DaoImpl">
<!-- 下面一句注释掉,使用注解时,不需要这句注入 -->
<!-- <property name="student" ref="student"/> -->
</bean>
3.测试
public class MyMain {
public static void main(String[] args) {
//读取配置文件
AbstractApplicationContext context = new ClassPathXmlApplicationContext("appContextAnnotat.xml");
//获得bean
IService service = (IService)context.getBean("service");
service.printStuInfo();
}
}
三、@Qualifier
@Qualifier(value = "限定标识符")
字段、方法、参数
当配置文件有多个同类型的Bean,@AutoWired注解就会无法识别,发生异常。通过@Qualifier注解指定名称,这样就可以确定一个Bean了。
在Bean的字段上添加@Qualifier注解:
public class DaoImpl implements IDao{
//指定id为student的bean
@Autowired
@Qualifier("student")
private Student student;
// 得到学生的信息
@Override
public String getStuInfo() {
return "id:"+student.getId() + " name:" + student.getName();
}
}
四、@Resource
@Resource:自动装配,默认根据名称(ByName)装配,如果指定name属性将根据名字装配
@Resource(name="name")
字段或setter方法
在Bean的字段上添加@Resource注解:
public class ServiceImpl implements IService{
@Resource(name="dao")
private IDao dao;
@Override
public void printStuInfo() {
System.out.println(dao.getStuInfo());
}
}
使用非常简单,和@Autowired不同的是可以指定name来根据名字注入。@Resource在没有指定name属性的情况下首先将根据setter方法对于的字段名查找资源,如果找不到再根据类型查找;
源码:
https://gitee.com/LuckZ/spring-xml-annotation-demo
https://github.com/LuckZZ/spring-xml-annotation-demo