Spring学习心得(8)-- IOC注解

来源:互联网 发布:全局安装node sass 编辑:程序博客网 时间:2024/06/01 14:11

引入:

在传统的编码中,我们使用xml文件,把一个类放到spring容器中,现在我们还可以使用注解的方式,把一个类放到spring容器中。

步骤:

首先,我们要引入的还是命名空间,命名空间与上面一个帖子里面的注解是一样的,所以在这里我们就不做讨论。

配置文件:

<!--             component:与bean的意思一样            base-package:表示包名,只从哪个包开始扫描类            -->            <context:component-scan base-package="cn.ansel.scan"></context:component-scan>
//在类的上方加入注解,@Component("a")public class Person implements Serializable {    @Resource(name="b")    private Student student;    public void showStudent(){        this.student.show();    }}@Component("b")public class Student implements Serializable {    public void show(){        System.out.println("student");    }}

component的属性有:这里写图片描述 
其中value的取值对应的是配置文件中bean的id值,如上我们写的@Component("b") 
相当于<bean id="b" class="cn.ansel.scan.Student"></bean>

测试类

public class annotationTest {    @Test    public void test(){        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");        Person person=(Person) applicationContext.getBean("person_annotation");        person.showStudent();    }}

运行测试类: 
这里写图片描述

流程解析:

1、开启spring容器,读取spring的配置文件 
2、根据配置文件中配置的<context:component-scan base-package="cn.ansel.scan"></context:component-scan> 
中的base-package中的包名开始查找下面中的哪些类使用了@Component,找到之后,为它们创建对象 
4、创建完对象,然后再看看刚刚创建对象的哪些对象中使用了@Resource,然后为他们的属性赋值(具体流程看上一个贴:DI注解)。 
5、然后就是客户端的调用 
6、关闭spring容器

xml与注解的区别:

1、xml文件书写比较麻烦,但是效率高 
2、注解书写简单,但是效率低 
3、关于xml与注解的书写,相对于类在Web上的传输效率来说可以忽略不计,但是如果你一个项目有成千上万个类的话,还是使用xml把类添加到spring容器中。





0 0
原创粉丝点击