更多11

注解注入顾名思义就是通过注解来实现注入,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依赖注入:注解注入总结的更多相关文章

  1. java 静态代码块和spring @value等注解注入顺序

      java 静态代码块和spring @value等注解注入顺序 问题所在 先上代码 java方法 @Value("${mf.cashost}") public static S ...

  2. Spring 3.0 注解注入详解

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...

  3. Spring系列之新注解配置+Spring集成junit+注解注入

    Spring系列之注解配置 Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率 你本来要写一段很长的代码来构造一个 ...

  4. Spring-构造注入&注解注入&代理模式&AOP

    1.   课程介绍 1.  依赖注入;(掌握) 2.  XML自动注入;(掌握) 3.  全注解配置;(掌握) 4.  代理模式;(掌握) 5.  AOP;(掌握) 依赖注入;(掌握) 2.1.  构 ...

  5. Spring入门_04_注解注入

    applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xm ...

  6. [转]Spring通过@Value注解注入属性的几种方式

    原文地址:https://blog.csdn.net/csujiangyu/article/details/50945486 ------------------------------------- ...

  7. Spring学习笔记1—依赖注入(构造器注入、set注入和注解注入)

    什么是依赖注入 在以前的java开发中,某个类中需要依赖其它类的方法时,通常是new一个依赖类再调用类实例的方法,这种方法耦合度太高并且不容易测试,spring提出了依赖注入的思想,即依赖类不由程序员 ...

  8. Spring构造器注入、set注入和注解注入

    记得刚开始学spring的时候,老师就反复的提到依赖注入和切面,平常的java开发中,在某个类中需要依赖其它类的方法,则通常是new一个依赖类再调用类实例的方法,这种方法耦合度太高并且不容易测试,sp ...

  9. spring常用的一些注解以及注解注入总结

    常用的spring注解有如下几种: @Controller@Service@Autowired@RequestMapping@RequestParam@ModelAttribute@Cacheable ...

随机推荐

  1. Django基础 - Debug设置为False后静态文件获取404

    当设置setting.py文件当中的DEBUG=FALSE后,Django会默认使用Web Server的静态文件处理,故若没设置好Web Server对静态文件的处理的话,会出现访问静态文件404的 ...

  2. m3u8字段意义解析

    m3u8字段意义解析 HLS,Http Live Streaming是由Apple公司定义的用于实时流传输的协议,HLS基于HTTP协议实现,传输内容包括两部分,一是M3U8描述文件,二是TS媒体文件 ...

  3. 找不到类型{0} 它在 ServiceHost 指令中提供为 Service 特性值

    由于我把binding改成wsHttpBinding,在web.config里也改了命名空间 services的类名也改成了跟 web.config对应的命名空间后 在添加引用后,出现了错误: “找不 ...

  4. 编写高质量iOS代码与OS X代码的effective 方法小结

    一.熟悉OC: 了解OC的起源: OC和C++,Java等面向对象语言类似,不过有很方面差别.因为该语言使用  消息结构而非函数调用. 消息结构和函数调用的区别:前者是在其运行时所应执行的代码由运行环 ...

  5. Stream 流操作

     Stream 类 先看下面的图 Stream 是所有流的抽象基类(不能被实例化,需要使用他的派生类FileStream/MemoryStream/BufferedStream).流是字节序列的抽象概 ...

  6. libtool: Version mismatch error 解决

    在编译一个软件的时候,在 ./configure 和 make  之后可能会出现如下错误: libtool: Version mismatch error.  This is libtool 2.4. ...

  7. 云计算之路-阿里云上:2014年6月12日14:40出现CPU 100%

    这是今天遇到的第2次故障,主站1台云服务器在14:40:33-14:41:09期间出现CPU突然跑满的状况,而CPU跑满之前,请求量并没有明显增长. 向阿里云提交之后,说晚上会对这台云服务器的虚拟机进 ...

  8. WINDOWS8.1安装ORACLE客户端及配置

    1.官方网站下载: instantclient-basic-win32-11.2.0.1.0.zip instantclient-sqlplus-win32-11.2.0.1.0.zip instan ...

  9. WCF 入门 (16)

    前言 上周回母校见了一下大学老师,还有些同学,发现差距还是挺大的...圈子不一样,真的就什么都不一样了.. 第16集 WCF中的Soap错误 Soap faults in WCF 首先简单介绍一下什么 ...

  10. 第十六章:脚本化HTTP

    写在本章内容前: 第十五章:事件处理 涉及到到较多的文字篇幅,介于个人精力问题,暂不更新.主要包含的内容有事件类型.注册事件处理程序.事件处理程序的调用.文档加载事件.鼠标事件.鼠标滚轮事件.拖放事件 ...