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里,创建被 ...
随机推荐
- sourcetree和Git的使用教程
1.简单的用Git管理项目. 2.怎样既要开发又要处理发布出去的版本bug情况. SourceTree是一个免费的Git图形化管理工具,mac下也可以安装. 下载地址:https://www.sour ...
- FBX BlendShape/Morph动画解析
目前fbx 2015.1中支持三种变形器:skinDeformer,blendShapeDeformer,vertexCacheDeformer.定义在fbxdeformer.h中: enum EDe ...
- poj2151--Check the difficulty of problems(概率dp第四弹,复杂的计算)
Check the difficulty of problems Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 5009 ...
- unity3D角色代码控制问题
///////////////2015/07/06//////// ///////////////by xbw////////////// //////////////环境 unity4.6.1// ...
- iOS改变UINavigationBar导航条标题颜色和字体
转自:http://www.2cto.com/kf/201311/260409.html iOS 5 以后 UINavigationController 可以 改变UINavigationBar导航条 ...
- 解决方式-在Mac系统中,Eclipse无法导入含有中文路径的project
1.改动eclipse.app/Contents/Info.plist.查找 <key>CFBundleExecutable<key> 在其上方加入下面代码 <? xml ...
- zookeeper 安装 配置集群
https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/ [root@znode01 src]# tar -xzvf zookeeper--alph ...
- C#中的 .NET 弱事件模式
引言 你可能知道,事件处理是内存泄漏的一个常见来源,它由不再使用的对象存留产生,你也许认为它们应该已经被回收了,但不是,并有充分的理由. 在这个短文中(期望如此),我会在 .Net 框架的上下文事件处 ...
- 【转】Oozie4.2.0配置安装实战
什么是Oozie? Oozie是一种Java Web应用程序,它运行在Java servlet容器——即Tomcat——中,并使用数据库来存储以下内容: 工作流定义 当前运行的工作流实例,包括实例的状 ...
- 在java web中获取该项目的根路径
在jsp页面中: <% String path = application.getRealPath("").replace("\\","\\\\ ...