您的位置:首页 > 编程语言 > Java开发

java EE开发之spring第一章:spring中的IOC和DI

2018-03-05 16:47 239 查看
一.Spring框架的概述:

1.什么是Spring:

Spring是分层的JavaSE/EE full-stack(一站式) 轻量级开源框架

* 分层:

* SUN提供的EE的三层结构:web层、业务层、数据访问层(持久层,集成层)

* Struts2是web层基于MVC设计模式框架.

* Hibernate是持久的一个ORM的框架.

* 一站式:

* Spring框架有对三层的每层解决方案:

* web层:Spring MVC.

* 持久层:JDBC Template

* 业务层:Spring的Bean管理.

2.Spring的核心:

IOC:(Inverse of Control 反转控制)

* 控制反转:将对象的创建权,交由Spring完成.

AOP:Aspect Oriented Programming 是 面向对象的功能延伸.不是替换面向对象,是用来解决OO中一些问题.

3.Spring的版本:

Spring3.x和Spring4.x Spring4需要整合hibernate4.

4.EJB:企业级JavaBean

EJB:SUN公司提出EE解决方案.

2002 : Expert One-to-One J2EE Design and Development

2004 : Expert One-to-One J2EE Development without EJB (EE开发真正需要使用的内容.)

5.Spring优点:

1.方便解耦,简化开发

* Spring就是一个大工厂,可以将所有对象创建和依赖关系维护,交给Spring管理

2.AOP编程的支持

* Spring提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能

3.声明式事务的支持

* 只需要通过配置就可以完成对事务的管理,而无需手动编程

4.方便程序的测试

* Spring对Junit4支持,可以通过注解方便的测试Spring程序

5.方便集成各种优秀框架

* Spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如:Struts、Hibernate、

MyBatis、Quartz等)的直接支持

6.降低JavaEE API的使用难度

* Spring 对JavaEE开发中非常难用的一些API(JDBC、JavaMail、远程调用等),都提供了封

装,使这些API应用难度大大降低

二.1.3.IOC和DI,Aop概念

以前我们程序中所有的对象自己new出来,效率太低,现在不能这样弄。为了帮助大家理解,以做鞋子的方式给大家做一个解释。

做鞋子(写程序)

原始做法

自己做 6个月 不能批量

工业时代

要求工厂做出我想要的鞋子——工厂生产 好处:价格降下来 重复使用 不需要关注对象细节

批量生产。

总结:把对象的new的权利,new的控制权给工厂 这种方式就叫:控制反转 inverse=true

IOC: Inverse Object Control

三.到底ioc怎么玩?

步骤一:创建3个类

1.创建RedPig类

public class RedPig {

private int age;

private String name;

…..get/set方法

}

2.BlackPig类

publi
4000
c class BlackPig{

private int age;

private String name;

…..get/set方法

}

3.创建工厂类RedPigFactory类

public class RedPigFactory{

public static RedPig createRedPig(){

RedPig rp = new RedPig();

rp.setAge(1);

rp.setName(“tom”);

return rp;

}

}

步骤二:测试:传统方式与ioc方式

原始社会

RedPig rp = new RedPig();

rp.setAge(1);
rp.setName("tom");


工业时代

RedPig rp = RedPigFactory.createRedPig();

总结:这就是工厂创建对象,将对象的控制权反转给工厂,ioc,这个与spring有什么关系,spring也有ioc,到底spring又是怎么样玩ioc的了?

四.spring中ioc的玩法

1.创建2个类

还是以刚才的猪类为例,不同的是 不需要工厂类 由spr类

2.导入spring框架包ing为我们提供工厂

spring-beans-3.2.0.RELEASE.jar

spring-context-3.2.0.RELEASE.jar

spring-core-3.2.0.RELEASE.jar

spring-expression-3.2.0.RELEASE.jar

开发的日志记录的包:

com.springsource.org.apache.commons.logging-1.1.1.jar— 用于整合其他的日志的 包(类似Hibernate中slf4j)

com.springsource.org.apache.log4j-1.2.15.jar

3.Spring核心配置文件

告诉spring哪些类需要工厂创建

<bean id="rp" class="com.accp.entity.RedPig">
<property name="age">
<value>10</value>
</property>
<property name="name">
<value>tom</value>
</property>
........
</bean>
<bean id="bp" class="com.accp.entity.BlackPig">
<constructor-arg>
<value>tom</value>
</constructor-arg>
<constructor-arg>
<value>1</value>
</constructor-arg>

</bean>


4.得到bean工厂的3种方式

1.resource方式 —java程序

Resource resource = new ClassPathResource("applicationContext.xml");
//FileSystemResource = new FileSystemResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
UsersBIZ biz = (UsersBIZ) factory.getBean("usersbiz");
Users users = new Users();
biz.insertUsers(users);


2.ApplicationContext方式–>单元测试

//classpath路径获取
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
UsersBIZ biz2 = (UsersBIZ)  context.getBean("usersbiz");
biz2.insertUsers(users);

ApplicationContext context =new  FileSystemXmlApplicationContext
("classpath:applicationContext.xm   l");
UserBiz ub =  (UserBiz)context.getBean("ub");
System.out.println(ub.add(3, 5));


3.web方式专门是跟web项目集成

从工厂不能从硬盘中直接读取spring的配置文件,只能从servletcontext中寻找spring的配置文件

WebApplicationContext webContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext())


六.BeanFactory与ApplicationContext区别?

ApplicationContext类继承了BeanFactory.

BeanFactory在使用到这个类的时候,getBean()方法的时候才会加载这个类.

ApplicationContext类加载配置文件的时候,创建所有的类.

ApplicationContext对BeanFactory提供了扩展:

* 国际化处理

* 事件传递

* Bean自动装配

* 各种不同应用层的Context实现

* 早期开发使用BeanFactory.

七.Spring框架加载配置文件:

ApplicationContext 应用上下文,加载Spring 框架配置文件

加载classpath:

new ClassPathXmlApplicationContext(“applicationContext.xml”);:加载classpath下面配置文件.

加载磁盘路径:

new FileSystemXmlApplicationContext(“applicationContext.xml”); :加载磁盘下配置文件.

八.IOC和DI(*)区别?**

IOC:控制反转:将对象的创建权,由Spring管理.

DI:依赖注入:在Spring创建对象的过程中,把对象依赖的属性注入到类中.

* 面向对象中对象之间的关系;

* 依赖:

public class A{

private B b;

}

* 继承:is a

* 聚合:

* 聚集:

* 组合:

九.MyEclipse配置XML提示:

Window—>xml catalog—>add 找到schema的位置 ,将复制的路径 copy指定位置,选择schema location.

十.IOC装配Bean:

1.Spring框架Bean实例化的方式:

提供了三种方式实例化Bean.

* 构造方法实例化:(默认无参数)

* 静态工厂实例化:

* 实例工厂实例化:

1.1.无参数构造方法的实例化:

<!-- 默认情况下使用的就是无参数的构造方法. -->
<bean id="bean1" class="com.kz.spring3.demo2.Bean1"></bean>


1.2.静态工厂实例化:

<!-- 第二种使用静态工厂实例化 -->
<bean id="bean2" class="com.kz.spring3.demo2.Bean2Factory"
factory-method="getBean2"></bean>


1.3.实例工厂实例化:

<!-- 第三种使用实例工厂实例化 -->
<bean id="bean3" factory-bean="bean3Factory"
factory-method="getBean3"></bean>
<bean id="bean3Factory" class="com.kz.spring3.demo2.Bean3Factory"/>


2.Bean的其他配置:

2.1.id和name的区别:

id遵守XML约束的id的约束.id约束保证这个属性的值是唯一的,而且必须以字母开始,可以使用字母、数字、连字符、下划线、句话、冒号

name没有这些要求

* 如果bean标签上没有配置id,那么name可以作为id.

* 开发中Spring和Struts1整合的时候, /login.

<bean name=”/login” class=””>


总结:现在的开发中都使用id属性即可.

2.2.类的作用范围:

scope属性 :

* singleton :单例的.(默认的值.)

* prototype :多例的.

* request :web开发中.创建了一个对象,将这个对象存入request范

围,request.setAttribute();

* session :web开发中.创建了一个对象,将这个对象存入session范

围,session.setAttribute();

* globalSession :一般用于Porlet应用环境.指的是分布式开发.不是porlet环

境,globalSession等同于session;

总结:实际开发中主要使用singleton,prototype

2.3.Bean的生命周期:

(1)配置Bean的初始化和销毁的方法:

(2)配置初始化和销毁的方法:

init-method=”setup”

destroy-method=”teardown”

执行销毁的时候,必须手动关闭工厂,而且只对scope=”singleton”有效.

(3)Bean的生命周期的11个步骤:

1.instantiate bean对象实例化

2.populate properties 封装属性

3.如果Bean实现BeanNameAware 执行 setBeanName

4.如果Bean实现BeanFactoryAware 或者 ApplicationContextAware 设置工厂

setBeanFactory 或者上下文对象 setApplicationContext

5.如果存在类实现 BeanPostProcessor(后处理Bean) ,执行

postProcessBeforeInitialization

6.如果Bean实现InitializingBean 执行 afterPropertiesSet

7.调用
<bean init-method="init">
指定初始化方法 init

8.如果存在类实现 BeanPostProcessor(处理Bean) ,执行

postProcessAfterInitialization

9.执行业务处理

10.如果Bean实现 DisposableBean 执行 destroy

11.调用
<bean destroy-method="customerDestroy">
指定销毁方法 customerDestroy

在CustomerService类的add方法之前进行权限校验?

3.Bean中属性注入:

Spring支持构造方法注入和setter方法注入:

3.1.构造器注入:

<bean id="car" class="com.kz.spring3.demo5.Car">
<!-- <constructor-arg name="name" value="宝马"/>
<constructor-arg name="price" value="1000000"/> -->
<constructor-arg index="0" type="java.lang.String" value="奔驰"/>
<constructor-arg index="1" type="java.lang.Double" value="2000000"/>
</bean>


3.2.setter方法注入:

<bean id="car2" class="com.kz.spring3.demo5.Car2">
<!-- <property>标签中name就是属性名称,value是普通属性的值,ref:引用其他的对象 -->
<property name="name" value="保时捷"/>
<property name="price" value="5000000"/>
</bean>


3.3.setter方法注入对象属性:

<property name="car2" ref="car2"/>


3.4.名称空间p:注入属性:

Spring2.5版本引入了名称空间p.

p:<属性名>=”xxx” 引入常量值

p:<属性名>-ref=”xxx” 引用其它Bean对象

引入名称空间:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.s d07c
pringframework.org/schema/beans                                 http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="car2" class="com.kz.spring3.demo5.Car2" p:name="宝马"
p:price="400000"/>
<bean id="person" class="com.kz.spring3.demo5.Person" p:name="童童"
p:car2-ref="car2"/>


3.5.SpEL:属性的注入:

Spring3.0提供注入属性方式:

语法:#{表达式}

<bean id="" value="#{表达式}">


<bean id="car2" class="com.kz.spring3.demo5.Car2">
<property name="name" value="#{'大众'}"></property>
<property name="price" value="#{'120000'}"></property>
</bean>

<bean id="person" class="com.kz.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="com.kz.spring3.demo5.PersonInfo">
<property name="name" value="张三"/>
</bean>


4.集合属性的注入:

<bean id="collectionBean" class="com.kz.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>


十一.加载分离配置文件:

一种写法:

ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("bean1.xml",”bean2.xml”);


二种方法:

<import resource="applicationContext2.xml"/>


十二.IOC装配Bean(注解方式)

12.1.Spring的注解装配Bean

Spring2.5 引入使用注解去定义Bean

@Component 描述Spring框架中Bean

Spring的框架中提供了与@Component注解等效的三个注解:

@Repository 用于对DAO实现类进行标注

@Service 用于对Service实现类进行标注

@Controller 用于对Controller实现类进行标注

* 三个注解为了后续版本进行增强的.

12.2.Bean的属性注入:

普通属性;

@Value(value=”itcast”)

private String info;

对象属性:

@Autowired:自动装配默认使用类型注入.

@Autowired

@Qualifier(“userDao”) — 按名称进行注入.

@Autowired

@Qualifier(“userDao”)

private UserDao userDao;

等价于

@Resource(name=”userDao”)

private UserDao userDao;

12.3.Bean其他的属性的配置:

配置Bean初始化方法和销毁方法:

* init-method 和 destroy-method.

@PostConstruct 初始化

@PreDestroy 销毁

配置Bean的作用范围:

@Scope

12.4.Spring3.0提供使用Java类定义Bean信息的方法

@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;
}


}

12.5.实际开发中使用XML还是注解?

XML:

* bean管理

*

注解;

* 注入属性的时候比较方便.

两种方式结合;一般使用XML注册Bean,使用注解进行属性的注入.

<context:annotation-config/>


@Autowired

@Qualifier(“orderDao”)

private OrderDao orderDao;

十三.Spring整合web开发:

正常整合Servlet和Spring没有问题的

但是每次执行Servlet的时候加载Spring配置,加载Spring环境.

* 解决办法:在Servlet的init方法中加载Spring配置文件?

* 当前这个Servlet可以使用,但是其他的Servlet的用不了了!!!

* 将加载的信息内容放到ServletContext中.ServletContext对象时全局的对象.服务器启动的时候创建的.在创建ServletContext的时候就加载Spring的环境.

* ServletContextListener:用于监听ServletContext对象的创建和销毁的.

导入;spring-web-3.2.0.RELEASE.jar

在web.xml中配置:

<listener> @kate ContextListener实现了ServletContextListener接口
<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>


修改程序的代码:

WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext applicationContext = (WebApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);


十四.Spring集成JUnit测试:

1.程序中有Junit环境.

2.导入一个jar包.spring与junit整合jar包.

* spring-test-3.2.0.RELEASE.jar

3.测试代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class SpringTest {
@Autowired
private UserService userService;

@Test
public void demo1(){
userService.sayHello();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: