Spring依赖注入:注解注入总结
注解注入顾名思义就是通过注解来实现注入,Spring和注入相关的常见注解有Autowired、Resource、Qualifier、Service、Controller、Repository、Component。
- Autowired是自动注入,自动从spring的上下文找到合适的bean来注入
- Resource用来指定名称注入
- Qualifier和Autowired配合使用,指定bean的名称
- Service,Controller,Repository分别标记类是Service层类,Controller层类,数据存储层的类,spring扫描注解配置时,会标记这些类要生成bean。
- Component是一种泛指,标记类是组件,spring扫描注解配置时,会标记这些类要生成bean。
上面的Autowired和Resource是用来修饰字段,构造函数,或者设置方法,并做注入的。而Service,Controller,Repository,Component则是用来修饰类,标记这些类要生成bean。
下面我们通过实例项目来看下spring注解注入的使用。
首先新建一个maven项目,并在pom中添加spring相关的依赖,如果不知道添加那些依赖,请参照上一篇文章。
然后新建CarDao类,给它添加@Repository注解,如下代码:
package cn.outofmemory.helloannotation; import org.springframework.stereotype.Repository; @Repository
public class CarDao { public void insertCar(String car) {
String insertMsg = String.format("inserting car %s", car);
System.out.println(insertMsg);
} }
新建CarService类,并给该类标注@Service注解,在这个类中定义CarDao的字段,并通过Autowired来修饰此字段,这样上面定义的CarDao类的实例就会自动注入到CarService的实例中了。
package cn.outofmemory.helloannotation; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service
public class CarService { @Autowired
private CarDao carDao; public void addCar(String car) {
this.carDao.insertCar(car);
}
}
注意:Autowired注解有一个可以为空的属性required,可以用来指定字段是否是必须的,如果是必需的,则在找不到合适的实例注入时会抛出异常。
下面我们在App.java中使用上面测试下注解注入:
package cn.outofmemory.helloannotation; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; /**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
ApplicationContext appContext = new AnnotationConfigApplicationContext("cn.outofmemory.helloannotation");
CarService service = appContext.getBean(CarService.class);
service.addCar("宝马");
}
}
在上面的main方法中首先我们初始化了appContext,他是AnnotationConfigApplicationContext,它的构造函数接受一个package的名称,来限定要扫描的package。然后就可以通过appContext的getBean方法获得CarService的实例了。
上面的例子非常简单,单纯的使用AnnotationConfigApplicationContext就可以了,但是在实际项目中情况往往没有这么简单,还是需要spring配置文件的。在spring配置文件中也可以通过下面的配置让spring自动扫描注解配置。
<!-- bean annotation driven -->
<context:annotation-config />
<context:component-scan base-package="cn.outofmemory.helloannotation" >
</context:component-scan>
下面我们看下混合使用spring配置和注解的例子,首先在项目中添加source folder,src/main/resources,并添加spring.xml, 其内容如下:
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <!-- bean annotation driven -->
<context:annotation-config />
<context:component-scan base-package="cn.outofmemory.helloannotation" >
</context:component-scan> <bean id="sqliteCarDao" class="cn.outofmemory.helloannotation.CarDao" >
<constructor-arg name="driver" value="sqlite"/>
</bean>
</beans>
在上面的配置文件中,我们通过context:annotation-config和context:component-sacn节点来指定要扫描注解注入,然后又定义了一个id为sqliteCarDao的bean,它的构造函数的driver值为sqlite。
我们修改下App.java使用xml配置文件,再运行下App看下会怎样。
package cn.outofmemory.helloannotation; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
//ApplicationContext appContext = new AnnotationConfigApplicationContext("cn.outofmemory.helloannotation"); ApplicationContext appContext = new ClassPathXmlApplicationContext("/spring.xml");
CarService service = appContext.getBean(CarService.class);
service.addCar("宝马");
}
}
运行程序发现输出为:inserting car 宝马 into mysql,显然CarService自动注入的CarDao使用了默认构造函数构造的实例。是否可以通过注解指定使用spring.xml中配置的sqliteCarDao呢?
我们可以修改下CarService类,通过Qualifier注解来指定要使用的bean的名字。
如下,在指定Autowired注解时,同时指定Qualifier注解指定bean的名字
@Autowired
@Qualifier("sqliteCarDao")
private CarDao carDao;
重新运行下App.java 这次输出的是inserting car 宝马 into sqlite,这次使用了spring.xml中配置的bean了。
在文中开头我们还提到了Resouce注解,这个注解可以指定名字注入,我们再次修改下CarService类:
@Resource(name="sqliteCarDao")
private CarDao carDao;
javax.annotation.Resource注解实现的效果和@Autowired+@Qualifier的效果是一样的。
Spring依赖注入:注解注入总结的更多相关文章
- java 静态代码块和spring @value等注解注入顺序
java 静态代码块和spring @value等注解注入顺序 问题所在 先上代码 java方法 @Value("${mf.cashost}") public static S ...
- Spring 3.0 注解注入详解
国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...
- Spring系列之新注解配置+Spring集成junit+注解注入
Spring系列之注解配置 Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率 你本来要写一段很长的代码来构造一个 ...
- Spring-构造注入&注解注入&代理模式&AOP
1. 课程介绍 1. 依赖注入;(掌握) 2. XML自动注入;(掌握) 3. 全注解配置;(掌握) 4. 代理模式;(掌握) 5. AOP;(掌握) 依赖注入;(掌握) 2.1. 构 ...
- Spring入门_04_注解注入
applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xm ...
- [转]Spring通过@Value注解注入属性的几种方式
原文地址:https://blog.csdn.net/csujiangyu/article/details/50945486 ------------------------------------- ...
- Spring学习笔记1—依赖注入(构造器注入、set注入和注解注入)
什么是依赖注入 在以前的java开发中,某个类中需要依赖其它类的方法时,通常是new一个依赖类再调用类实例的方法,这种方法耦合度太高并且不容易测试,spring提出了依赖注入的思想,即依赖类不由程序员 ...
- Spring构造器注入、set注入和注解注入
记得刚开始学spring的时候,老师就反复的提到依赖注入和切面,平常的java开发中,在某个类中需要依赖其它类的方法,则通常是new一个依赖类再调用类实例的方法,这种方法耦合度太高并且不容易测试,sp ...
- spring常用的一些注解以及注解注入总结
常用的spring注解有如下几种: @Controller@Service@Autowired@RequestMapping@RequestParam@ModelAttribute@Cacheable ...
随机推荐
- DWZ(JUI)的lookupGroup增加回调函数
DWZ 是一个很好的富客户端框架 lookupGroup也是一个必用到的东东,但没有回调函数,后期处理相当的不便. 修改其dwz.database.js 增加几行,就能实行一个很好的回调. 使用就方便 ...
- [CareerCup] 9.4 Subsets 子集合
9.4 Write a method to return all subsets of a set. LeetCode上的原题,请参见我之前的博客Subsets 子集合和Subsets II 子集合之 ...
- IM架构(一)JSQMessagesViewController
JSQMessagesViewController 是 Jesse Squires 开发的一个消息界面的 UI 库.
- 启动图实现:UIScrollView+UIPageControl简单实现
#import "MJViewController.h"#import "RootViewController.h" @interface MJViewCont ...
- C#基础之垃圾回收
1.托管资源的回收 我们都知道C#托管资源的回收由GC全权负责控制,可是什么时候GC会回收垃圾呢?一般出现以下情况会回收垃圾:手动调用GC.Collect()强制回收:第0代对象内存已满:应用程序域被 ...
- [转]Extundelete--数据恢复软件
前言 作为一名运维人员,保证数据的安全是根本职责,所以在维护系统的时候,要慎之又慎,但是有时难免会出现数据被误删除的情况,在这个时候该如何快速.有效地恢复数据显得至关重要,extundelete就是其 ...
- 基于微信红包插件的原理实现android任何APP自动发送评论(已开源)
背景 地址:https://github.com/huijimuhe/postman 核心就是android的AccessibilityService,回复功能api需要23以上版本才行. 其实很像在 ...
- windows网络编程的一些理论
参考自<VC++深入详解> 这是我在看书时记录下来的东西. 注:下面的Socket其实都应该是socket 第14章网络编程 Socket是连接应用程序与网络驱动程序的桥梁,Socket在 ...
- Android Studio之gradle的配置与介绍
1.gradle的简单介绍 Gradle是可以用于Android开发的新一代的Build System,也是Android Studio默认的build工具.其实Gradle脚本是基于一种JVM语言- ...
- Dandelion - Distributed Computing on GPU Clusters
linq on GPUs 非常期待中 看起来很cool,期望早点面世