Spring 依赖注入(DI)的注解
Spring中想要使用注解进行依赖注入,需要进行如下配置:
<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">
<context:annotation-config/>
</beans>
Spring自带依赖注入的注解
@Required,该注解必须用是setter方法上面,目的是强制要求提供setter所需数据,否则报错。
例如,BeanA中的字段field,有一个setField( T field)方法。当在该方法上使用了@Required之后,在XML中创建BeanA时就必须给出设置field所需的数据。
如下所示:
package o1.bean;
import org.springframework.beans.factory.annotation.Required;
public class BeanA {
private String message;
public String getMessage(){
return message;
}
@Required //只能放在setter上,在XML配置BeanA时必须指定setter注入,否则在Spring容器启动时将抛出异常
public void setMessage(String message){
this.message = message;
}
}
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!--开启注解支持-->
<context:annotation-config/> <bean class="o1.bean.BeanA">
<!--因为有了@Required,所以这里必须提供,否则报错-->
<property name="message" ref="message"/>
</bean> <bean name="message" class="java.lang.String">
<constructor-arg index="0" value="hello world"/>
</bean> </beans>
package o1; import o1.bean.BeanA;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class A {
private ApplicationContext applicationContext; @Before
public void setUp(){
applicationContext=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
} @Test
public void run1(){
BeanA bean = applicationContext.getBean(BeanA.class);
System.out.println(bean.getMessage());
} }
@Autowired(required=true)
自动注入,required=true的作用与@Required相同。
可用于构造器、字段、方法。
默认根据参数类型自动装配,但必须只能有一个候选项(required=false则可以允许0个候选项)。
@Value(value="SpEL")
可用于字段、方法(@Autowired method)。
如:
@Value(value="#{message}")
private String message;
@Autowired
public void initMessage(@Value(value = "#{message}") String message) {
this.message = message;
}
@Qualifier(value="限定标识符")
可用于方法、字段、参数。
配合@Autowired使用,可用于多个候选项的情况。
实例如下:
package o1.bean; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import javax.sql.DataSource; public class BeanB {
private DataSource dataSourceA;
private DataSource dataSourceB; public DataSource getDataSourceA(){
return dataSourceA;
} @Autowired
public void initDataSource(@Qualifier( "mysqlDataSource2" ) DataSource dataSource){ //
this.dataSourceA =dataSource;
} public DataSource getDataSourceB(){
return dataSourceB;
} @Autowired
public void setDataSourceB(@Qualifier( "mysqlDataSource1" ) DataSource dataSourceB){
this.dataSourceB = dataSourceB;
}
}
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!--开启注解支持-->
<context:annotation-config/>
<context:property-placeholder location="db.properties"/> <bean class="o1.bean.BeanB"/> <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<qualifier type="org.springframework.beans.factory.annotation.Qualifier" value="mysqlDataSource1"/> <!--type可以省略-->
<property name="driverClassName" value="${driverClass}"/>
<property name="url" value="${jdbcUrl_1}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
</bean> <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<qualifier type="org.springframework.beans.factory.annotation.Qualifier" value="mysqlDataSource2"/>
<property name="driverClassName" value="${driverClass}"/>
<property name="url" value="${jdbcUrl_2}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
</bean> </beans>
package o1; import o1.bean.BeanB;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class B {
private ApplicationContext applicationContext; @Before
public void setUp(){
applicationContext=new ClassPathXmlApplicationContext("classpath:applicationContextB.xml");
} @Test
public void run1(){
BeanB bean = applicationContext.getBean(BeanB.class);
System.out.println(bean.getDataSourceA());
System.out.println(bean.getDataSourceB()); }
}
db.properties
driverClass=com.mysql.jdbc.Driver
jdbcUrl_1=jdbc\:mysql\://localhost\:3306/testdb1?useUnicode=true&characterEncoding=UTF8
jdbcUrl_2=jdbc\:mysql\://localhost\:3306/testdb2?useUnicode=true&characterEncoding=UTF8
user=root
password=root
如果有几个常用的DataSource,那么可以自定义注解来使用,而不必每次都是@Qualifier("xx")。如下:
自定义@MySQL和@Oracle
package o1.customize_qualifier; import org.springframework.beans.factory.annotation.Qualifier; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Target( {ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE} )
@Retention( RetentionPolicy.RUNTIME )
@Qualifier
public @interface MySQL {
}
package o1.customize_qualifier; import org.springframework.beans.factory.annotation.Qualifier; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Target( {ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE} )
@Retention( RetentionPolicy.RUNTIME )
@Qualifier
public @interface Oracle {
}
使用qualifier来限定需要注入的bean:
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!--开启注解支持-->
<context:annotation-config/> <bean class="o1.bean.BeanC"/> <bean id="dataSource1" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<qualifier type="o1.customize_qualifier.MySQL" value="mysqlDataSource"/><!--value可以省略!-->
</bean> <bean id="dataSource2" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<qualifier type="o1.customize_qualifier.Oracle" value="oracleDataSource"/>
</bean> </beans>
要被注入的bean:
package o1.bean; import o1.customize_qualifier.MySQL;
import o1.customize_qualifier.Oracle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import javax.sql.DataSource; public class BeanC {
private DataSource dataSourceA;
private DataSource dataSourceB; @Autowired
public void initDataSource(@MySQL DataSource dataSourceA, @Oracle DataSource dataSourceB){
this.dataSourceA = dataSourceA;
this.dataSourceB = dataSourceB;
} public DataSource getDataSourceA(){
return dataSourceA;
} public DataSource getDataSourceB(){
return dataSourceB;
} }
测试:
package o1; import o1.bean.BeanB;
import o1.bean.BeanC;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import javax.sql.DataSource; public class C {
private ApplicationContext applicationContext; @Before
public void setUp(){
applicationContext=new ClassPathXmlApplicationContext("classpath:applicationContextC.xml");
} @Test
public void run1(){
BeanC bean = applicationContext.getBean(BeanC.class);
DataSource dataSource1 = applicationContext.getBean("dataSource1", DataSource.class);
DataSource dataSource2 = applicationContext.getBean("dataSource2", DataSource.class); Assert.assertEquals(dataSource1, bean.getDataSourceA());
Assert.assertEquals(dataSource2, bean.getDataSourceB());
}
}
==================================================
使用<context:annotation-config/>标签来开启注解形式的依赖注入。
使用<context:component-scan/>标签来表示需要要自动注册Bean定义,而通过base-package属性指定扫描的类路径位置。
注意,<context:component-scan/>默认开启了annotation-config。
使用<aop:aspectj-autoproxy/>标签开启Spring对@AspectJ风格切面的支持。
@AspectJ风格的切面可以通过@Compenent注解标识其为Spring管理Bean,而@Aspect注解不能被Spring自动识别并注册为Bean,必须通过@Component注解来完成。
<<<未完待续>>>
声明:源自张开涛的Spring教程,再加工。
Spring 依赖注入(DI)的注解的更多相关文章
- Spring 依赖注入(DI) 的三种方式 和 对集合类型的注入
// 分别省略了getter setter public class Student { private String name; private int age; private Teacher t ...
- Helloworld之Spring依赖注入/控制反转(DI/IoC)版
Helloworld之Spring依赖注入/控制反转(DI/IoC)版 作者:雨水, 日期:2014-10-29 摘要:本文主要用于培训刚開始学习的人理解Spring中的依赖注入的基本概念. 先介绍依 ...
- Spring框架学习笔记(1)——控制反转IOC与依赖注入DI
Spring框架的主要作用,就是提供了一个容器,使用该容器就可以创建并管理对象.比如说Dao类等,又或者是具有多依赖关系的类(Student类中包含有Teacher类的成员变量) Spring有两个核 ...
- 1.4 Spring 依赖注入(DI)和控制反转(IOC)详解
自己开发了一个股票智能分析软件,功能很强大,需要的点击下面的链接获取: https://www.cnblogs.com/bclshuai/p/11380657.html 1.1 Spring 依赖注 ...
- 小白都能看懂的 Spring 源码揭秘之依赖注入(DI)源码分析
目录 前言 依赖注入的入口方法 依赖注入流程分析 AbstractBeanFactory#getBean AbstractBeanFactory#doGetBean AbstractAutowireC ...
- Spring依赖注入:注解注入总结
更多11 spring 依赖注入 注解 java 注解注入顾名思义就是通过注解来实现注入,Spring和注入相关的常见注解有Autowired.Resource.Qualifier.S ...
- spring(3)------控制反转(IOC)/依赖注入(DI)
一.spring核心概念理解 控制反转: 控制反转即IoC (Inversion of Control).它把传统上由程序代码直接操控的对象的调用权交给容器.通过容器来实现对象组件的装配和管理. 所谓 ...
- SSM框架之Spring(3)IOC及依赖注入(基于注解的实现)
Spring(3)IOC及依赖注入(基于注解的实现) 学习基于注解的 IoC 配置,大家脑海里首先得有一个认知,即注解配置和 xml 配置要实现的功能都是一样 的,都是要降低程序间的耦合.只是配置的形 ...
- Spring Boot2(007):关于Spring beans、依赖注入 和 @SpringBootApplication 注解
一.关于Spring beans 和 依赖注入(Dependency Injection) spring boot 和 Spring 全家桶无缝衔接,开发过程中可以很轻松地使用 Spring 全家桶的 ...
- Spring(2):依赖注入DI
依赖注入DI 当某个角色(可能是一个Java实例,调用者)需要另一个角色(另一个Java实例,被调用者)的协助时,在 传统的程序设计过程中,通常由调用者来创建被调用者的实例.但在Spring里,创建被 ...
随机推荐
- Linux 普通进程 后台进程 守护进程(转)
一.普通进程与后台进程 默认情况下,进程是在前台运行的,这时就把shell给占据了,我们无法进行其它操作.对于那些没有交互的进程,很多时候,我们希望将其在后台启动,可以在启动参数的时候加一个'& ...
- 常用IP核
前言 记录自己用到的模块,随时补充. 主要分类: 一.常用模块 1-FIFO FIFO分为两种,一是输入输出时钟相同(Common clock)的 fifo ;二是输入输出时钟不相同(Independ ...
- .NET执行SQL插入时间的问题
错误描述: 一个项目,源码是BOSS给的,部署到网上了,运行没有问题,可是在本地运行,就会有问题,问题在于往一些表插入记录的时候,本地不管怎么样都插入不了,而网上就可以插入,都是相同的一份代码 解决: ...
- modelsim与debussy联调环境的搭建
为了方便查看波形,找来了一款软件——debussy,它的一个优点是任你查看设计内信号,只需一个波形文件,如FSDB文件.而不用像modelsim那样想看某些信号,添加了之后还要重新编译仿真,浪费了很多 ...
- ISE和Modelsim联合仿真(详细步骤讲解)
ISE和Modelsim联合仿真(转) 地址:http://www.cnblogs.com/feitian629/archive/2013/07/13/3188192.html 相信很多人会遇到过这个 ...
- AAA含义图解
来源: <FreeRADIUS Beginner's Guide> 这本书 1,认证 2,授权 3,审计
- ping域名和ping IP时速度不同的原因
不知道大家在ping的时候有没有遇到过这样的问题:当你ping一个域名的时候,ping结果返回得很慢,但是如果直接ping这个域名的ip,结果却快很多. 直接ping ip的时候,每两次发包之间没有明 ...
- C#compiler
http://www.cnblogs.com/Ninputer/archive/2011/06/12/2078671.html Compilers - Managed Profile-Guided O ...
- C++ 11 std::function std::bind使用
cocos new 出新的项目之后,仔细阅读代码,才发现了一句3.0区别于2.0的代码: auto closeItem = MenuItemImage::create( "CloseNorm ...
- Python 按当前日期(年、月、日)创建多级目录的方法
先看实际效果,现在时间2018.4.26 使用python脚本按照年月日生成多级目录,创建的目录可以将系统生成的日志文件放入其中,方便查阅,代码如下: #!/usr/bin/env python #c ...