Spring 用注解实现IOC控制反转

    1、建包cn.google.annotation.scan    用于类扫描

    2、导入 Student.java,Person.java,applicationContext-scan-annotation.xml

    3、在 applicationContext-scan-annotation.xml 中

			<?xml version="1.0" encoding="UTF-8"?>
			<beans xmlns="http://www.springframework.org/schema/beans"
				xmlns:context="http://www.springframework.org/schema/context"
				xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
				xsi:schemaLocation="http://www.springframework.org/schema/beans
				   http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				   http://www.springframework.org/schema/context
				   http://www.springframework.org/schema/context/spring-context-2.5.xsd">
			    <!-- 
				类扫描的注解解析器
				   component 指的就是一个类
				   base-package 在该包及子包中进行扫描
			     -->
				<context:component-scan  base-package="cn.google.annotation.scan"></context:component-scan>
			</beans>
    4、在 Person.java 中:

			@Component("a")
			public  class  Person{
				@Resource(name="b")
				private  Student  student;

				public  void  showStudent(){
					this.students.show();
				}
			}

        在 Student.java 中:

			@Component("b")
			public  class  Student{
				public  void  show(){
					s.o.p("student");
				}
			}

    5、建测试类 ScanTest.java
		public  class  ScanTest  extends  SpringInit{
			@Test
			public  void  testPerson(){
				Person  person = (Person)context.getBean("a");
				person.showStudent();
			}
		}

        结果:创建student对象,执行 showStudent() 方法。


    6、总结
        类扫描的注解:
            1、加入命名空间,同DI

            2、注解解析器变成“类扫描”
                <context:component-scan  base-package="cn.google.annotation.scan"></context:component-scan>
                ·该注解解析器包含了两个功能:“依赖注入”和“类扫描”
                ·在 base-package 包以及子包下查找所有的类

            3、如果一个类上加了 @Component 注解,就会进行如下的法则:value 属性匹配 <bean> 中的id值
                如果其 value 属性的值为""
                    @Component
                    pulbic  class  Person(){} == <bean  id="person"  class="...Person">

                如果其value 属性不为“”
                    @Component("p")
                    pulbic  class  Person(){} == <bean  id="p"  class="...Person">


            4、执行 @Resource 法则

    

xml与注解:
    1、xml 效率高但麻烦,
    2、注解书写简单,但是效率低



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值