spring依赖注入的注解

    1.在我们配置文件中要引入spring依赖注入的scheme,然后引入spring注解属性

2.编写我们的实体类如上面person,student简单的实体类,在我们person类中

public class Person {
 @Resource(name="student")
// @Autowired  //按照类型进行匹配
// @Qualifier("student")
 private Student student;
 public Student getStudent() {
  return student;
 }
}
3.编写我们的测试类
public class AnnotationTest {
 @Test
 public void testAnnotation(){
  ApplicationContext context =
    new ClassPathXmlApplicationContext("applicationContext.xml");
  Person person = (Person)context.getBean("person");
  person.getStudent().say();
 }
}
总结:原理
 *    1、当启动spring容器的时候,创建两个对象
 *    2、当spring容器解析到
 *       <context:annotation-config></context:annotation-config>
 *        spring容器会在spring容器管理的bean的范围内查找这些类的属性上面是否加了@Resource注解
 *    3、spring解析@Resource注解的name属性
 *      如果name属性为""
 *              说明该注解根本没有写name属性
 *              spring容器会得到该注解所在的属性的名称和spring容器中的id做匹配,如果匹配成功,则赋值
 *                                                               如果匹配不成功,则按照类型进行匹配
 *          如果name属性的值不为""
 *               则按照name属性的值和spring的id做匹配,如果匹配成功,则赋值,不成功,则报错
在我们第二步骤中有2种方式,一个是我们java@Resource另一个是spring特有的 @Autowired ,@Qualifier这2中方法都可以实现注入
自动扫描注解配置:
 1.在我们的配置文件中配置
  <!--
     component:把一个类放入到spring容器中,该类就是一个component
     在base-package指定的包及子包下扫描所有的类
    -->
   <context:component-scan base-package="com.itheima12.spring.scan">
   </context:component-scan>
2.在我们的类中
@Component("person")
public class Person {
  @Resource(name="student")
 private Student student;
 public Student getStudent() {
  return student;
 }
}
以上配置详解:
 原理
 *   1、启动spring容器,spring容器解析配置文件
 *   2、当解析到<context:component-scan base-package="com.itheima12.spring.scan">
      </context:component-scan>
         就会在上面指定的包及子包中扫描所有的类,看哪些类上面有@Component注解
     3、如果有该注解,则有如下的规则:
          @Component
          public class Person{
         
          }
          ==
          <bean id="person" class"..."/>   id的值:把类的第一个字母变成小写,其他字母不变
         
          @Component("person")这种是定义id=person
          public class Person{
         
          }
          ==
          <bean id="person"  class=".."/>
      4、按照@Resource注解的规则进行赋值

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值