Spring注解开发(学习笔记)

Spring注解开发
优点:方便、简单、快捷
缺点:第三方jar包,没法给他们添加@Component注解,没法用
IOC(控制反转)
不使用new关键字进行实例化对象,而是通过反射机制使用全限定类名进行实例化,实现细节由spring完成。

初始化环境
在maven项目下,在pom.xml项目对象管理文件中添加spring项目所需的依赖。
spring的核心依赖(上下文依赖)

<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.13.RELEASE</version>
</dependency>
spring的测试依赖,需要导入junit依赖(可选)
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-test</artifactId>
		<version>RELEASE</version>
		<scope>test</scope>
	</dependency>

log4j日志依赖(可选),需要写配置文件
	<dependency>
		<groupId>log4j</groupId>
		<artifactId>log4j</artifactId>
		<version>1.2.12</version>
	</dependency>

spring注解
工作机制
当使用
ApplicationContextapplicationContext=newAnnotationConfigApplicationContext(配置类名.class);初始化上下文环境时,
被@ComponentScan扫描到的@Component会实例化
Object object=applicationContext.getBean(Object.class);获取被spring创建好的对象

@Configuration:配置类,一般该类是@ComponentScan
@ComponentScan:扫描到所有@Component类,ComponentScan只能扫描到当前包或者子包中的@Component,可以在注解后面添加包名扩大它的扫描范围
	@Configuration
	@ComponentScan("pakagename") 
	publicclassAppConfig{
	}
@Component:组件,被@ComponentScan发现扫描到,从而使spring上下文发现,可以由spring通过反射机制进行实例化对象,面向接口开发时应在实现类上注解
@Autowired:自动装配,一般修饰成员变量(便捷)、set方法、有参构造方法(效率高)、或者自定义方法(会自动执行,比set方法更加方便一些),它会根据类名自动获取spring创建好的对象自动初始化

required关键字:spring默认使必须装配@Autowired修饰的对象,该对象的类不存在或者不是@Component时,装配失败会报错,如果自动装配是非必须的,则需要在@Autowired注解后面添加required=false;如@Autowired(required=false),默认为true。使用required关键字时需要进行非空检查,否则会发生空指针异常。

面向接口开发时,一般是实现接口,而不是实现类,如果一个接口出现多个实现类的话,那么应该为接口装配哪个类的对象,解决冲突呢?
1、使用@Primary来修饰首选bean,但是有时候也会造成冲突
2、在@Component上添加@Qualifier("id")(或者直接使用@Component"id"),在装配的对象的时候也用添加注解@Qualifier("id"),就可以解决实现类的冲突了
3、更简单的,可以不用在@Component上添加id,那么默认使用类名作为id(类名首字母小写),然后再使用注解@Qualifier("id")
以上方式为Spring的标准解决方案,下面为java的标准解决方案
使用@Resource(name="id")注解来代替 @Autowired 与 @Qualifier("id")两个注解

在实际开发三层架构中:
@Repository在Dao层中可以代替@Component
@Service在service层中可以代替@Component
@Controller在Web层中可以代替@Component
它们具有同样的功能,但是针对性更强。

注解开发总结

定义配置  
@Configuration
@ComponentScan

定义组件
@Component
@Autowired
@Autowired(required=false)

自动装配歧义性
@Primary
@Qualifier
@Resource

分层架构中定义组件
@Controller
@Service
@Repository

Spring测试环境
@Runwith
@ContextConfiguration     
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章