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 ...
随机推荐
- logback+spring实践
配置文件名称使用: logback-spring.xml 配置user.home是jvm传过来的系统参数,可以直接使用 <property name="LOG_PATH&quo ...
- Java学习笔记day04_数组
1.switch case switch语句中表达式的数据类型是有要求的: JDK 1.0 ~ 1.4 , 数据类型接受byte, short, int, char JDK 1.5 , 数据类型接受b ...
- python学习2(转载)
一.流程控制之while循环 语法:while 条件: 循环体else: else语句(当条件不成立的时候执行这里 和break没关系) 判断条件是否成立. 如果成立执行循环体.然后再次判断条件,.. ...
- 查看Oracle当前连接数
SQL> select count(*) from v$session #当前的连接数 SQL> Select count(*) from v$session where status=' ...
- ArrayList中进行删除操作引发的问题
1.普通for遍历 for(int i=0;i<list.size();i++){ if(list.get(i).equals("a")) list.remove(i); } ...
- 以多进程读取oss符合条件的数据为例,综合使用多进程间的通信、获取多进程的数据
import datetime import sys import oss2 from itertools import islice import pandas as pd import re im ...
- sqlserver 2012 部署详解
01,下载 官网下载: https://www.microsoft.com/zh-cn/download/details.aspx?id=29066 02,安装 检查系统环境配置 成功了就继续,其他的 ...
- 性能测试工具Jmeter03-功能概要
Jmeter工具组成部分 资源生成器:用于生成测试过程中服务器.负载机的资源代码.(LR中的VuGen) 用户运行器:通常是一个脚本运行引擎,根据脚本要求模拟指定的用户行为.(LR中的Controll ...
- hduoj 2546饭卡
饭卡 Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submissi ...
- Android下常见的内存泄露 经典
转自:http://www.linuxidc.com/Linux/2011-10/44785.htm 因为Android使用Java作为开发语言,很多人在使用会不注意内存的问题. 于是有时遇到程序运行 ...