您的位置:首页 > 编程语言 > Java开发

Spring 一二事(7) - annotation

2016-03-22 11:49 489 查看
之前的文章大多都是一带而过,一方面比较简单,一方面不是用的注解形式

在企业开发中,主要还是使用的注解来进行开发的

1   <!--
component:把一个类放入到spring容器中,该类就是一个component
在base-package指定的包及子包下扫描所有的类
-->
<context:component-scan base-package="com.lee.spring011.scan"></context:component-scan>


主要还是用 @Resource,另外2个不常用

package com.lee.spring010.DI.annotation;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Person {

@Resource
//    @Resource(name="studentA")
//    @Autowired 纯粹按照类型进行匹配
//    @Qualifier("studentA")
private Student studentA;

//    public Student getStudentA() {
//        return studentA;
//    }

public void tell() {
studentA.sayHello();
}

}


package com.lee.spring010.DI.annotation;

public class Student {

public void sayHello() {
System.out.println("Hello! I am a student...nathan!");
}

}


测试:

package com.lee.spring010.DI.annotation;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AnnotationTest {

/**
* 原理
*    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做匹配,如果匹配成功,则赋值,不成功,则报错
*   说明:
*       注解只能用于引用类型
*       注解写法比较简单,但是效率比较低
*       xml写法比较复杂,但是效率比较高
*/
@Test
public void testPerson() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Person personA = (Person)context.getBean("personA");
//        personA.getStudentA().sayHello();
personA.tell();
}

}


github地址:https://github.com/leechenxiang/maven-spring001-helloworld
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: