Spring 一二事(7) - annotation
2016-03-22 11:49
489 查看
之前的文章大多都是一带而过,一方面比较简单,一方面不是用的注解形式
在企业开发中,主要还是使用的注解来进行开发的
主要还是用 @Resource,另外2个不常用
测试:
github地址:https://github.com/leechenxiang/maven-spring001-helloworld
在企业开发中,主要还是使用的注解来进行开发的
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
相关文章推荐
- javaWeb开发模式
- Spring Security(07)——缓存UserDetails
- 全面分析 Spring 的编程式事务管理及声明式事务管理(转)
- JAVA学习总结(2)
- java,this和super使用实例
- Spring 初始化过程跟踪
- 20160322 javaweb 学习笔记--response验证码实现
- java几种常见加密算法小试
- java环境变量的配置
- Java的MD5加密和解密
- JAVA中equals()和==比较
- JAVA回调
- java读取excel文件
- [转]Ubuntu 12.04 安装 JDK 7 / JDK8 的两种方式
- Leetcode: 8. String to Integer (atoi)(JAVA)
- java 中提供的默认的快速排序的实现 .
- org.springframework.dao.support
- Eclipse中自动生成versionName的一种方法
- Spring 一二事(6) - IOC MVC 简易搭建
- 记录java 流(实现简单的文件读写)