IOC、注入
转:https://blog.csdn.net/lutianfeiml/article/details/51731219
实际开发中使用XML还是注解
- XML:
- bean管理
- 注解:
- 注入属性的时候比较方便
- 两种方式结合;一般使用XML注册Bean,使用注解进行属性的注入
Spring支持
- 构造方法注入
- setter方法注入
构造器注入
- 使用构造方法注入,在Spring配置文件中,通过
<constructor-arg>设置注入的属性 (可以通过index或者type注入)

setter方法注入
- 使用setter方法注入,在Spring配置文件中,通过
<property>设置注入的属性

<bean id="car2" class="cn.itcast.spring3.demo5.Car2">
<!-- <property>标签中name就是属性名称,value是普通属性的值,ref:引用其他的对象 -->
<property name="name" value="保时捷"/>
<property name="price" value="5000000"/>
</bean>
- 1
- 2
- 3
- 4
- 5
setter方法注入对象属性
<property>标签中name就是属性名称,value是普通属性的值,ref:引用其他的对象

名称空间p:注入属性
Spring2.5版本引入了
名称空间pp:<属性名>="xxx"引入常量值p:<属性名>-ref="xxx"引用其它Bean对象
引入名称空间:
xmlns:p="http://www.springframework.org/schema/p"

xml:
<bean id="car2" class="cn.itcast.spring3.demo5.Car2" p:name="宝马" p:price="400000"/>
<bean id="person" class="cn.itcast.spring3.demo5.Person" p:name="童童" p:car2-ref="car2"/>
- 1
- 2
- 3
SpEL:属性的注入
- Spring3.0提供注入属性方式:
- 语法:
<bean id="" value="#{表达式}">#{'神回复:哈哈'}使用字符串#{topicId3}使用另一个bean#{topicId4.content.toUpperCase()}使用指定名属性,并使用方法#{T(java.lang.Math).PI}使用静态字段或方法
<bean id="car2" class="cn.itcast.spring3.demo5.Car2">
<property name="name" value="#{'大众'}"></property>
<property name="price" value="#{'120000'}"></property>
</bean>
<bean id="person" class="cn.itcast.spring3.demo5.Person">
<!--<property name="name" value="#{personInfo.name}"/>-->
<property name="name" value="#{personInfo.showName()}"/>
<property name="car2" value="#{car2}"/>
</bean>
<bean id="personInfo" class="cn.itcast.spring3.demo5.PersonInfo">
<property name="name" value="张三"/>
</bean>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
SpEL : 集合属性的注入 – List(数组)

SpEL : 集合类型属性注入 – Set

SpEL : 集合类型属性注入 – Map

SpEL :集合类型属性注入 – Properties

- 综合案例
<bean id="collectionBean" class="cn.itcast.spring3.demo6.CollectionBean">
<!-- 注入List集合 -->
<property name="list">
<list>
<value>童童</value>
<value>小凤</value>
</list>
</property>
<!-- 注入set集合 -->
<property name="set">
<set>
<value>杜宏</value>
<value>如花</value>
</set>
</property>
<!-- 注入map集合 -->
<property name="map">
<map>
<entry key="刚刚" value="111"/>
<entry key="娇娇" value="333"/>
</map>
</property>
<property name="properties">
<props>
<prop key="username">root</prop>
<prop key="password">123</prop>
</props>
</property>
</bean>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
多配置文件的加载
第一种写法:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml",”bean2.xml”);
第二种方法:
<import resource="applicationContext2.xml"/>
Bean的属性注入–基于注解方式
IoC容器装配Bean , 基于注解配置方式
Spring2.5 引入注解去定义Bean
@Component描述Spring框架中Bean

Xml:头文件中加入context路径:
xmlns:context=http://www.springframework.org/schema/context- 最好直接从
dsd-config.html中复制过来相应的代码段
- 最好直接从
<?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.xsd">
<!-- bean definitions here -->
</beans>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 配置提示操作
- 将红框中地址复制到
Key中

- 将红框中地址复制到
- 引入component-scan标签:
<context:component-scan base-package="cn.itcast.spring3"/>,告诉Spring要去扫描哪些包下的类。

- Spring的框架中提供了与
@Component注解等效的三个注解:
@Repository用于对DAO实现类进行标注
@Service用于对Service实现类进行标注
@Controller用于对Controller实现类进行标注 - 三个注解是为了让标注类本身的用途清晰,Spring在后续版本会对其增强
自动装配 Bean
- 使用
@Autowired进行自动注入 @Service标注业务类@Repository标注DAO@Autowired默认按照类型进行注入- 如果存在两个相同Bean类型,则按照名称注入
- @Autowired 注入时可以针对成员变量或者setter方法

- 通过@Autowired的required属性,设置一定要找到匹配的Bean,默认为true,为false时表示对异常不关心。
- 使用
@Qualifier指定注入Bean的名称- 使用
Qualifier指定Bean名称后,注解Bean必须指定相同名称

- 使用
普通属性
- @Value(value=”itcast”)
- private String info;
对象属性
- 按类型注入
- @Autowired:自动装配默认使用类型注入.
- 按名称进行注入
- @Autowired 中有一个属性required,默认为true,为false时表示对异常不关心。
- @Qualifier(“userDao”) 按名称进行注入.
标准注解@Resource
Spring提供对JSR-250中定义
@Resource标准注解的支持@Resource和@Autowired注解功能相似下面两个例子等价
@Autowired
@Qualifier("userDao")
private UserDao userDao;
- 1
- 2
- 3
@Resource(name="userDao")
private UserDao userDao;
- 1
- 2
Bean其他的属性的配置
- 配置Bean初始化方法和销毁方法:
- init-method 和 destroy-method.
@PostConstruct: 初始化@PreDestroy: 销毁

配置Bean的作用范围
- 使用注解配置的Bean和
<bean>配置的一样,默认作用范围都是singleton- @Scope注解用于指定Bean的作用范围

Spring3.0可以 使用Java类提供Bean定义信息
Spring3.0以JavaConfig为核心,提供使用Java类定义Bean信息的方法
@Configuration指定POJO类为Spring提供Bean定义信息,代表此类就是一个配置类。@Bean提供一个Bean定义信息
之前已经通过
component-scan标签对配置类进行了扫描,故这里不需要再进行手动配置扫描了。

@Configuration
public class BeanConfig {
@Bean(name="car")
public Car showCar(){
Car car = new Car();
car.setName("长安");
car.setPrice(40000d);
return car;
}
@Bean(name="product")
public Product initProduct(){
Product product = new Product();
product.setName("空调");
product.setPrice(3000d);
return product;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
实际开发中使用XML还是注解
- XML:
- bean管理
- 注解:
- 注入属性的时候比较方便
- 两种方式结合;一般使用XML注册Bean,使用注解进行属性的注入

Spring整合web开发
正常整合Servlet和Spring没有问题的,但是每次执行Servlet的时候加载Spring配置以及加载Spring环境
解决办法:
- 将加载的信息内容放到
ServletContext中.ServletContext对象是全局的对象。服务器启动的时候创建的,在创建ServletContext的时候就加载Spring的环境。 ServletContextListener:用于监听ServletContext对象的创建和销毁的.- 以上解决方法可以通过导入Spring web开发jar包来解决 :
spring-web-3.2.0.RELEASE.jar
- 将加载的信息内容放到
web.xml中的配置
- 将Spring容器初始化,交由web容器负责
- 配置核心监听器 ContextLoaderListener
- 配置全局参数contextConfigLocation
- 用于指定Spring的框架的配置文件位置(因为:applicationContext.xml文件与默认位置不一致)

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
获得WebApplicationContext对象
- 因为Spring容器已经交由web容器初始化和管理,获得WebApplicationContext对象,需要依赖ServletContext对象 通常在Servlet中完成:
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
- 1
- 另一种方式
WebApplicationContext applicationContext = (WebApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
- 1
eg:
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name></display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>cn.itcast.servlet.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/userServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
- UserServlet & UserService
public class UserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");*/
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
UserService userService = (UserService) applicationContext
.getBean("userService");
userService.sayHello();
}
public class UserService {
public void sayHello(){
System.out.println("Hello Spring web...");
}
}
IOC、注入的更多相关文章
- 使用JAVA实现的一个简单IOC注入实例
https://blog.csdn.net/echoshinian100/article/details/77977823 欲登高而望远,勿筑台于流沙 RSS订阅 原 使用JAVA实现的一个简单IOC ...
- Spring第四天,BeanPostProcessor源码分析,彻底搞懂IOC注入及注解优先级问题!
- 关于Container容器以及IoC注入机制的认识
container 容器的概念: 1 container 是一个Java 所编写的程序,用于对象之间之间管理对象关系. 主要的java EE 容器如下: Java容器类包含List.ArrayList ...
- Spring IOC 注入方式
依赖注入通常有如下两种方式: ①设值注入:IOC容器使用属性的Setter方法来注入被依赖的实例. 设值注入是指IOC容器使用属性的Setter方法来注入被依赖的实例.这种注入方式简单.直观,因而在S ...
- Entity Famework 的通过IOC注入实现
1. 前言 最近刚换了一家公司,由于之前的公司代码并没有用到项目框架,需要我整理下NHibernate与Entity Framework之间的区别及适用性.并写出相关的示例代码 面试的时候吹的牛,得把 ...
- Unity IOC注入详细配置(MVC,WebApi)
一直想写一篇关于unity 详细的配置信息的文章,也算是自我总结吧 先介绍了unity , Unity是微软官方推荐使用的轻型的IOC框架,支持各种方式的注入 ,使用来解耦的利器. 获取unity 的 ...
- Spring IOC 注入方式详解 附代码
引言 Spring框架作为优秀的开源框架之一,深受各大Java开发者的追捧,相信对于大家来说并不陌生,Spring之所以这么流行,少不了他的两大核心技术IOC和IOP.我们这里重点讲述Spring框架 ...
- Spring学习总结(5)——IOC注入方式总结
一.构造注入 在类被实例化的时候,它的构造方法被调用并且只能调用一次.所以它被用于类的初始化操作.<constructor-arg>是<bean>标签的子标签.通过其<v ...
- Spring的DI(Ioc) - 注入bean 和 基本数据类型
注入bean有两种方式: 注入其他bean: 方式一 <bean id="orderDao" class="cn.itcast.service.OrderDaoBe ...
- Ioc注入方式写dubbo client(非set beans)
@Autowired注解的方式注解 Spring框架中进行注入式,使用@Autowired. @Autowired可以对成员变量.方法和构造函数进行标注,来完成自动装配的工作,这里必须明确:@Auto ...
随机推荐
- mybatis CDATA引起的查询失败
<![CDATA[ ]]> 在被CDATA包围的所有字符串不会被mybatis解析, 直接写入sql了 CDATA应该只用在特殊字符前后,不能用在<if> <foreac ...
- 复制虚拟机出现”适配器 的mac地址在保留地址范围内‘’
首先我的虚拟机是复制出来的,选择我已经移到,但是结果会出现了以下情况,导致了我无法ping 通,先看下提示: 使用:ipconfig –all 命令查寻,果然再现有打开的虚拟机中,存在两个mac地址相 ...
- thinkPHP 模板操作
1.assign赋值 $this->assign('title','模板操作'); $this->assign('bests',$bests);//$bests是二维数组 2.变量的输出 ...
- oracle序列的缓存
在高并发的数据库系统中,序列的缓存也要相应的调大.现在看看数据库自己的一个高并发序列的定义. 当我们向数据库发送一个请求时,监听接待,然后oracle会启动一个后台进程(这个进程就是通常所说的数据库并 ...
- 二分搜索 - Binary Search
二分搜索是一种在有序数组中寻找目标值的经典方法,也就是说使用前提是『有序数组』.非常简单的题中『有序』特征非常明显,但更多时候可能需要我们自己去构造『有序数组』.下面我们从最基本的二分搜索开始逐步深入 ...
- Win 10 Enable .net framework 3.5 error (Error code:0x800F081F )
在下面页面enable .net frramwork 3.5时,发生0x800F081F错误. 解决方案: 1. 在如下链接下载Win10 版的microsoft-windows-netfx3-ond ...
- robotframework 常用快捷键
重命名——>F2 执行用例——>F8 创建新工程——>ctrl+n 创建新测试套——>ctrl+shift+f 创建新用例——>ctrl+shift+t 创建新关键字—— ...
- ubuntu下安装录屏软件
sudo add-apt-repository ppa:maarten-baert/simplescreenrecorder sudo apt-get update sudo apt-get inst ...
- rsync+inotify实现数据的实时同步更新
rsync可以实现触发式的文件同步,但是通过crontab守护进程方式进行触发,同步的数据和实际数据会有差异,而inotify可以监控文件系统的各种变化,当文件有任何变动时,就触发rsync同步,这样 ...
- WEB服务器、网站、域名、IP地址、DNS服务器之间的关系
域名首先指向你的服务器,这个过程叫解析. 服务器分成好多小块,每小块叫一个空间或者一个虚拟主机. 所以当你输入你的域名以后,服务器收到你域名的访问信息,但不知道要打开这么多个小块中的那一个.所以要 ...