Spring 一二事(7)

之前的文章大多都是一带而过,一方面比较简单,一方面不是用的注解形式

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

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

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

 1 package com.lee.spring010.DI.annotation;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.beans.factory.annotation.Qualifier;
 7 
 8 public class Person {
 9     
10     @Resource
11 //    @Resource(name="studentA")
12 //    @Autowired 纯粹按照类型进行匹配
13 //    @Qualifier("studentA")
14     private Student studentA;
15 
16 //    public Student getStudentA() {
17 //        return studentA;
18 //    }
19     
20     public void tell() {
21         studentA.sayHello();
22     }
23 
24     
25 }
1 package com.lee.spring010.DI.annotation;
2 
3 public class Student {
4     
5     public void sayHello() {
6         System.out.println("Hello! I am a student...nathan!");
7     }
8 
9 }

测试:

 1 package com.lee.spring010.DI.annotation;
 2 
 3 import org.junit.Test;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.support.ClassPathXmlApplicationContext;
 6 
 7 public class AnnotationTest {
 8 
 9     /**
10      * 原理
11      *    1、当启动spring容器的时候,创建两个对象
12      *    2、当spring容器解析到
13      *             <context:annotation-config></context:annotation-config>
14      *        spring容器会在spring容器管理的bean的范围内查找这些类的属性上面是否加了@Resource注解
15      *    3、spring解析@Resource注解的name属性
16      *            如果name属性为""
17      *              说明该注解根本没有写name属性
18      *              spring容器会得到该注解所在的属性的名称和spring容器中的id做匹配,如果匹配成功,则赋值
19      *                                                               如果匹配不成功,则按照类型进行匹配
20      *          如果name属性的值不为""
21      *               则按照name属性的值和spring的id做匹配,如果匹配成功,则赋值,不成功,则报错
22      *   说明:
23      *       注解只能用于引用类型
24      *       注解写法比较简单,但是效率比较低
25      *       xml写法比较复杂,但是效率比较高
26      */
27     @Test
28     public void testPerson() {
29         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
30         Person personA = (Person)context.getBean("personA");
31 //        personA.getStudentA().sayHello();
32         personA.tell();
33     }
34 
35 }

github地址:https://github.com/leechenxiang/maven-spring001-helloworld

原文地址:https://www.cnblogs.com/leechenxiang/p/5305687.html