spring六种种依赖注入方式
- Set注入
- package com.bless.springdemo.action;
- public class SpringAction {
- //注入对象springDao
- private SpringDao springDao;
- //一定要写被注入对象的set方法
- public void setSpringDao(SpringDao springDao) {
- this.springDao = springDao;
- }
- public void ok(){
- springDao.ok();
- }
- }
- <!--配置bean,配置后该类由spring管理-->
- <bean name="springAction" class="com.bless.springdemo.action.SpringAction">
- <!--(1)依赖注入,配置当前类中相应的属性-->
- <property name="springDao" ref="springDao"></property>
- </bean>
- <bean name="springDao" class="com.bless.springdemo.dao.impl.SpringDaoImpl"></bean>
- 构造器注入
- public class SpringAction {
- //注入对象springDao
- private SpringDao springDao;
- private User user;
- public SpringAction(SpringDao springDao,User user){
- this.springDao = springDao;
- this.user = user;
- System.out.println("构造方法调用springDao和user");
- }
- public void save(){
- user.setName("卡卡");
- springDao.save(user);
- }
- }
- <!--配置bean,配置后该类由spring管理-->
- <bean name="springAction" class="com.bless.springdemo.action.SpringAction">
- <!--(2)创建构造器注入,如果主类有带参的构造方法则需添加此配置-->
- <constructor-arg ref="springDao"></constructor-arg>
- <constructor-arg ref="user"></constructor-arg>
- </bean>
- <bean name="springDao" class="com.bless.springdemo.dao.impl.SpringDaoImpl"></bean>
- <bean name="user" class="com.bless.springdemo.vo.User"></bean>
- <bean name="springAction" class="com.bless.springdemo.action.SpringAction">
- <constructor-arg index="0" ref="springDao"></constructor-arg>
- <constructor-arg index="1" ref="user"></constructor-arg>
- </bean>
- <constructor-arg type="java.lang.String" ref=""/>
- 静态工厂的方法注入
- package com.bless.springdemo.factory;
- import com.bless.springdemo.dao.FactoryDao;
- import com.bless.springdemo.dao.impl.FactoryDaoImpl;
- import com.bless.springdemo.dao.impl.StaticFacotryDaoImpl;
- public class DaoFactory {
- //静态工厂
- public static final FactoryDao getStaticFactoryDaoImpl(){
- return new StaticFacotryDaoImpl();
- }
- }
- public class SpringAction {
- //注入对象
- private FactoryDao staticFactoryDao;
- public void staticFactoryOk(){
- staticFactoryDao.saveFactory();
- }
- //注入对象的set方法
- public void setStaticFactoryDao(FactoryDao staticFactoryDao) {
- this.staticFactoryDao = staticFactoryDao;
- }
- }
- <!--配置bean,配置后该类由spring管理-->
- <bean name="springAction" class="com.bless.springdemo.action.SpringAction" >
- <!--(3)使用静态工厂的方法注入对象,对应下面的配置文件(3)-->
- <property name="staticFactoryDao" ref="staticFactoryDao"></property>
- </property>
- </bean>
- <!--(3)此处获取对象的方式是从工厂类中获取静态方法-->
- <bean name="staticFactoryDao" class="com.bless.springdemo.factory.DaoFactory" factory-method="getStaticFactoryDaoImpl"></bean>
- 实例工厂的方法注入
- public class DaoFactory {
- //实例工厂
- public FactoryDao getFactoryDaoImpl(){
- return new FactoryDaoImpl();
- }
- }
- public class SpringAction {
- //注入对象
- private FactoryDao factoryDao;
- public void factoryOk(){
- factoryDao.saveFactory();
- }
- public void setFactoryDao(FactoryDao factoryDao) {
- this.factoryDao = factoryDao;
- }
- }
- <!--配置bean,配置后该类由spring管理-->
- <bean name="springAction" class="com.bless.springdemo.action.SpringAction">
- <!--(4)使用实例工厂的方法注入对象,对应下面的配置文件(4)-->
- <property name="factoryDao" ref="factoryDao"></property>
- </bean>
- <!--(4)此处获取对象的方式是从工厂类中获取实例方法-->
- <bean name="daoFactory" class="com.bless.springdemo.factory.DaoFactory"></bean>
- <bean name="factoryDao" factory-bean="daoFactory" factory-method="getFactoryDaoImpl"></bean>
- 总结
- <bean name="..." class="..." scope="prototype">
- Spring的依赖注入(接口注入)
- 2009-11-26 10:06 148人阅读 评论(0) 收藏 举报
- 这篇文章来谈谈《Spring Framework 开发参考手册》的3.3.3.1小节中的Lookup方法注入。
- 仔细看看文档,这种方法主要是用在Singleton的Object中使用非Singleton的Bean时,通过lookup-method的
- 那个方法来取得非Singleton的Bean。一般用的不多,在用这种定义之前最好想明白你的需求。
- · 先建立一个包:javamxj.spring.basic.lookup ,然后把以下5个文件放在这个包下。
- Hello.java.
- package javamxj.spring.basic.lookup;
- public interface Hello {
- public Random getRandom();
- public abstract Random createRandom();
- }
- Random.java
- package javamxj.spring.basic.lookup;
- public class Random {
- private int i = (int) (100 * Math.random());
- public void printRandom() {
- System.out.println("输出随机整数: " + i);
- }
- }
- HelloAbstract.java
- package javamxj.spring.basic.lookup;
- public abstract class HelloAbstract implements Hello {
- private Random random;
- public Random getRandom() {
- return random;
- }
- public void setRandom(Random random) {
- this.random = random;
- }
- public abstract Random createRandom();
- }
- beans.xml
- <?xml version="1.0" encoding="GBK"?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
- <beans>
- <bean id="ran" class="javamxj.spring.basic.lookup.Random" singleton="false"/>
- <bean id="hello" class="javamxj.spring.basic.lookup.HelloAbstract">
- <lookup-method name="createRandom" bean="ran"/>
- <property name="random">
- <ref local="ran"/>
- </property>
- </bean>
- </beans>
- Main.java
- package javamxj.spring.basic.lookup;
- import org.springframework.beans.factory.BeanFactory;
- import org.springframework.beans.factory.xml.XmlBeanFactory;
- import org.springframework.core.io.ClassPathResource;
- import org.springframework.core.io.Resource;
- public class Main {
- public static void main(String[] args) {
- Resource res = new ClassPathResource( "javamxj/spring/basic/lookup/beans.xml");
- BeanFactory ft = new XmlBeanFactory(res);
- Hello h = (Hello) ft.getBean("hello");
- Random r1 = h.getRandom();
- Random r2 = h.getRandom();
- System.out.println("没有采用Lookup方法注入:");
- System.out.println("Random 的两个实例指向同一个引用:" + (r1 == r2));
- r1.printRandom();
- r2.printRandom();
- Random r3 = h.createRandom();
- Random r4 = h.createRandom();
- System.out.println("/n采用Lookup方法注入:");
- System.out.println("Random 的两个实例指向同一个引用:" + (r3 == r4));
- r3.printRandom();
- r4.printRandom();
- }
- }
- 简单说明一下:
- · Hello是一个接口类,实现面向接口编程。
- · Random类用来输出随机整数。
- · HelloAbstract是一个抽象类,包含了一个属性:random,还包含一个抽象方法createRandom(),如果这个方法不是抽象的,spring会重写已有的实现。
- · beans.xml中定义了两个bean,ran指向Rondom类,注意它不是singleton的;hello指向HelloAbstract类,其中的random属性指向ran,createRandom方法也指向ran。
- · 在Main类中,Hello类分别利用getRandom()和createRandom()方法来调用Random类。
- · 这次需要将 spring-framework主目录/lib/cglib 目录中的cglib-nodep-2.1_2.jar加入到项目的 Libraries中,使用其中的动态代理。
- 运行结果:
- 没有采用Lookup方法注入:
- Random 的两个实例指向同一个引用:true
- 输出随机整数: 98
- 输出随机整数: 98
- 采用Lookup方法注入:
- Random 的两个实例指向同一个引用:false
- 输出随机整数: 51
- 输出随机整数: 26
- 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/javamxj/archive/2005/08/17/456600.aspx
我的理解:接口注入其实是,通过配置Spring的lookup-method,及返回值 ,可以返回接口中方法的返回值而不需要实现接口中的抽象方法
注解注入顾名思义就是通过注解来实现注入,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六种种依赖注入方式的更多相关文章
- spring四种依赖注入方式(转)
spring四种依赖注入方式!! 平常的java开发中,程序员在某个类中需要依赖其它类的方法,则通常是new一个依赖类再调用类实例的方法,这种开发存在的问题是new的类实例不好统一管理,spring提 ...
- spring 四种依赖注入方式以及注解注入方式
平常的java开发中,程序员在某个类中需要依赖其它类的方法,则通常是new一个依赖类再调用类实例的方法,这种开发存在的问题是new的类实例不好统一管理,spring提出了依赖注入的思想,即依赖类不由程 ...
- spring几种依赖注入方式以及ref-local/bean,factory-bean,factory-method区别联系
平常的java开发中,程序员在某个类中需要依赖其它类的方法,则通常是new一个依赖类再调用类实例的方法,这种开发存在的问题是new的类实例不好统一管理,spring提出了依赖注入的思想,即依赖类不由程 ...
- spring四种依赖注入方式
一.Set注入 这是最简单的注入方式,假设有一个SpringAction,类中需要实例化一个SpringDao对象,那么就可以定义一个private的SpringDao成员变量,然后创建SpringD ...
- 深入浅出spring IOC中三种依赖注入方式
深入浅出spring IOC中三种依赖注入方式 spring的核心思想是IOC和AOP,IOC-控制反转,是一个重要的面向对象编程的法则来消减计算机程序的耦合问题,控制反转一般分为两种类型,依赖注入和 ...
- 转:深入浅出spring IOC中四种依赖注入方式
转:https://blog.csdn.net/u010800201/article/details/72674420 深入浅出spring IOC中四种依赖注入方式 PS:前三种是我转载的,第四种是 ...
- 【SSH系列】深入浅出spring IOC中三种依赖注入方式
spring的核心思想是IOC和AOP,IOC-控制反转,是一个重要的面向对象编程的法则来消减计算机程序的耦合问题,控制反转一般分为两种类型,依赖注入和依赖查找,依赖什么?为什么需要依赖?注入什么?控 ...
- Spring学习(十八)Bean 的三种依赖注入方式介绍
依赖注入:让调用类对某一接口实现类的依赖关系由第三方注入,以移除调用类对某一接口实现类的依赖.接下来将详细的向大家介绍Spring容器支持的三种依赖注入的方式以及具体配置方法:• 属性注入方法• ...
- 给力啊!这篇Spring Bean的依赖注入方式笔记总结真的到位,没见过写的这么细的
1. Bean的依赖注入概念 依赖注入(Dependency Injection):它是 Spring 框架核心 IOC 的具体实现.在编写程序时,通过控制反转,把对象的创建交给了 Spring,但是 ...
随机推荐
- 开源HTML5 Canvas游戏Runtime发布
Cantk-Runtime是通用的HTML5 Canvas 2D游戏引擎运行库,让HTML5游戏的性能飞起来.Cantk-Runtime以PhoneGap插件的方式提供,从此结束PhoneGap低性能 ...
- Machine Learning for hackers读书笔记(三)分类:垃圾邮件过滤
#定义函数,打开每一个文件,找到空行,将空行后的文本返回为一个字符串向量,该向量只有一个元素,就是空行之后的所有文本拼接之后的字符串 #很多邮件都包含了非ASCII字符,因此设为latin1就可以读取 ...
- media query ie8- 兼容实现总结
虽然说响应式设计的理想状态是,需对pc/移动各种终端进行响应:但是现实是高分辨率的pc端与手机终端屏幕相差太大,像电商这样有大量图片和文字信息的同时排版要求精准的页面,设计一个同时适应高分辨率pc又适 ...
- MyBatis框架Maven资源
<!-- MyBatis框架 --> <dependency> <groupId>org.mybatis</groupId> <artifac ...
- Permutation Sequence [LeetCode]
The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the p ...
- NPOI相关
总结一下工作中遇到的NPOI以及在ASP.NET MVC中的使用 http://www.cnblogs.com/fenglingyi/p/4750323.html
- python 将数据随机分为训练集和测试集
# -*- coding: utf-8 -*- """ Created on Tue Jun 23 15:24:19 2015 @author: hd "&qu ...
- C++中颜色的设置
1.改变整个控制台的颜色用 system("color 0A"); 其中color后面的0是背景色代号,A是前景色代号.各颜色代码如下: 0=黑色 1=蓝色 2=绿色 3=湖蓝色 ...
- cl.exe
http://blog.csdn.net/happyanger6/article/details/7589016
- 关于JDBC
脑补一下JDBC基础知识,原文链接:http://docs.oracle.com/javase/tutorial/jdbc/basics/gettingstarted.html If you are ...