热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Spring:IOC依赖注入

在Spring中实现依赖注入有两种方式,分别是通过注解的方式和通过xml的方式,以下案例是在Spring3.x版本进行讲解。一、使用注解的方式实现IO

    在Spring中实现依赖注入有两种方式,分别是通过注解的方式和通过xml的方式,以下案例是在Spring3.x版本进行讲解。

一、使用注解的方式实现IOC

1.1、导入Spring类库


1.2、编写数据访问层DAO

这里面只是提供了一个空的类,我们的目的是为了测试在Service层中是否可以成功的将这个Dao类注入。通过@Repository注解来标注Dao

package com.dao;import org.springframework.stereotype.Repository;/*** * 配置DAO* * @author thinkpad**/
@Repository("userDao")
public class UserDao {}


1.3、编写服务层Service

我们通过@Service注解来标注Service

package com.service;import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;import com.dao.UserDao;/*** 配置Service* * @author thinkpad**/
@Service("userService")
@Scope("singleton") //单实例
//@Scope("prototype") //多实例
public class UserService {@Value("用户服务")private String info;// @Autowired// @Qualifier("userDao")@Resource(name = "userDao")private UserDao dao;/*** 初始化注解*/@PostConstructpublic void setup() {System.out.println("对象初始化");}/*** 销毁注解*/@PreDestroypublic void teardown() {System.out.println("对象销毁");}@Overridepublic String toString() {return "info:" + this.info + ",dao:" + this.dao;}
}


1.4、在applicationContext.xml中配置注解扫描


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.xsd">


1.5、测试

package test;import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.service.UserService;public class JTest {@Testpublic void test1() {ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");UserService en = (UserService) ctx.getBean("userService");System.out.println(en);UserService en2 = (UserService) ctx.getBean("userService");System.out.println(en.equals(en2));ctx.close();}}


1.6、运行结果


二、使用XML的方式实现IOC

1.1、导入Spring类库


1.2、要注入的实体对象

package test.entity;public class EntityInner {private String name;public void setName(String name) {this.name = name;}public String getName() {return name;}@Overridepublic String toString() {return "Inner姓名:" + this.name;}}package test.entity;public class Entity1 {private String name;public Entity1(String name) {this.name = name;}@Overridepublic String toString() {return "姓名:" + this.name;}
}package test.entity;public class Entity2 {private String name;public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "姓名:" + this.name;}
}package test.entity;public class Entity3 {private String name;private EntityInner inner;public void setName(String name) {this.name = name;}public void setInner(EntityInner inner) {this.inner = inner;}@Overridepublic String toString() {return "姓名:"+this.name + ",inner:"+this.inner.toString();}
}package test.entity;import java.util.List;
import java.util.Map;
import java.util.Properties;public class Entity4 {private List cities;private Map persons;private Properties users;public List getCities() {return cities;}public void setCities(List cities) {this.cities = cities;}public Map getPersons() {return persons;}public void setPersons(Map persons) {this.persons = persons;}public Properties getUsers() {return users;}public void setUsers(Properties users) {this.users = users;}}


1.3、在applicationContext.xml中配置注解扫描

applicationContext.xml



applicationContext2.xml


北京上海杭州admin123456



1.4、测试

package test;import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import test.entity.Entity1;
import test.entity.Entity2;
import test.entity.Entity3;
import test.entity.Entity4;public class JTest {/*** 通过Setter方法注入依赖对象*/@Testpublic void test1() {ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");Entity1 en = (Entity1) cxt.getBean("entity2");System.out.println(en.toString());}/*** 通过构造器注入依赖对象*/@Testpublic void test1_1() {ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");Entity2 en = (Entity2) cxt.getBean("entity1");System.out.println(en.toString());}/*** 注入实体*/@Testpublic void test2() {ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");Entity3 en = (Entity3) cxt.getBean("entity5");System.out.println(en.toString());}/*** 注入集合*/@Testpublic void test3() {ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");Entity4 en = (Entity4) cxt.getBean("entity6");System.out.println(en.getCities());System.out.println(en.getPersons());System.out.println(en.getUsers());}
}

四、源代码

Spring通过注解实现IOC

Spring通过xml实现IOC


推荐阅读
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 解决java.lang.IllegalStateException: ApplicationEventMulticaster not initialized错误的方法和原因
    本文介绍了解决java.lang.IllegalStateException: ApplicationEventMulticaster not initialized错误的方法和原因。其中包括修改包名、解决service name重复、处理jar包冲突和添加maven依赖等解决方案。同时推荐了一个人工智能学习网站,该网站内容通俗易懂,风趣幽默,值得一看。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • Java实战之电影在线观看系统的实现
    本文介绍了Java实战之电影在线观看系统的实现过程。首先对项目进行了简述,然后展示了系统的效果图。接着介绍了系统的核心代码,包括后台用户管理控制器、电影管理控制器和前台电影控制器。最后对项目的环境配置和使用的技术进行了说明,包括JSP、Spring、SpringMVC、MyBatis、html、css、JavaScript、JQuery、Ajax、layui和maven等。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • Webmin远程命令执行漏洞复现及防护方法
    本文介绍了Webmin远程命令执行漏洞CVE-2019-15107的漏洞详情和复现方法,同时提供了防护方法。漏洞存在于Webmin的找回密码页面中,攻击者无需权限即可注入命令并执行任意系统命令。文章还提供了相关参考链接和搭建靶场的步骤。此外,还指出了参考链接中的数据包不准确的问题,并解释了漏洞触发的条件。最后,给出了防护方法以避免受到该漏洞的攻击。 ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • FeatureRequestIsyourfeaturerequestrelatedtoaproblem?Please ... [详细]
  • 本文介绍了南邮ctf-web的writeup,包括签到题和md5 collision。在CTF比赛和渗透测试中,可以通过查看源代码、代码注释、页面隐藏元素、超链接和HTTP响应头部来寻找flag或提示信息。利用PHP弱类型,可以发现md5('QNKCDZO')='0e830400451993494058024219903391'和md5('240610708')='0e462097431906509019562988736854'。 ... [详细]
  • 本文介绍了Android 7的学习笔记总结,包括最新的移动架构视频、大厂安卓面试真题和项目实战源码讲义。同时还分享了开源的完整内容,并提醒读者在使用FileProvider适配时要注意不同模块的AndroidManfiest.xml中配置的xml文件名必须不同,否则会出现问题。 ... [详细]
  • 本文介绍了如何使用C#制作Java+Mysql+Tomcat环境安装程序,实现一键式安装。通过将JDK、Mysql、Tomcat三者制作成一个安装包,解决了客户在安装软件时的复杂配置和繁琐问题,便于管理软件版本和系统集成。具体步骤包括配置JDK环境变量和安装Mysql服务,其中使用了MySQL Server 5.5社区版和my.ini文件。安装方法为通过命令行将目录转到mysql的bin目录下,执行mysqld --install MySQL5命令。 ... [详细]
  • Spring学习(4):Spring管理对象之间的关联关系
    本文是关于Spring学习的第四篇文章,讲述了Spring框架中管理对象之间的关联关系。文章介绍了MessageService类和MessagePrinter类的实现,并解释了它们之间的关联关系。通过学习本文,读者可以了解Spring框架中对象之间的关联关系的概念和实现方式。 ... [详细]
author-avatar
骁炉
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有