Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。

  • Spring的好处

1.方便解耦,简化开发:

  • Spring就是一个大工厂,专门负责生成Bean,可以将所有对象创建和依赖关系维护由Spring管理

2.AOP编程的支持:

  • Spring提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能
  • 声明式事务的支持:只需要通过配置就可以完成对事务的管理,而无需手动编程

3.方便程序的测试:

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

4.方便集成各种优秀框架:

  • Spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如:Struts、Hibernate、MyBatis、Quartz等)的支持

5.降低JavaEE API的使用难度Spring:

  • 对JavaEE开发中一些难用的API(JDBC、JavaMail、远程调webservice用等),都提供了封装,使这些API应用难度大大降低

  • 控制反转IOC

Inverse of Control 反转控制的概念,就是将原本在程序中手动创建UserService对象的控制权,交由Spring框架管理,简单说,就是创建UserService对象控制权被反转到了Spring框架。

示例:

/src/beans.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"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd" >
<bean id="userService" class="com.chichung.service.impl.UserServiceImpl">
</bean>
</beans>

如果表示层需要new一个service对象,则:

public class Test {
public static void main(String[] args) {
// UserService service = new UserServiceImpl(); // 原来创建service对象的方式
// service.add();
// Spring框架创建对象的方式
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserService userService1 = (UserService) context.getBean("userService");
userService1.add();
}
}

  • 依赖注入DI(xml)

Dependency Injection 依赖注入,在Spring框架负责创建Bean对象时,动态的将依赖对象注入到Bean组件。

示例:

在UserService中提供一个get/set的name方法,在beans.xml中通过property去注入

public class UserServiceImpl implements UserService {
private String name; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Override
public void add() {
System.out.println("业务层"+name);
}
}

/src/beans.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"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd" >
<bean id="userService" class="com.chichung.service.impl.UserServiceImpl">
<property name="name" value="chichung"></property>
</bean>
</beans>

还有另一种方法是用命名空间p来注入,很少用

<?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:p
= "http://www.springframework.org/schema/p"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd" >
<bean id="userService" class="com.chichung.service.impl.UserServiceImpl" p:name="chichung">
</bean>
</beans>

如果没有setter方法,也可以通过构造方法来注入。

例如有一个Student类

public class Student {
private String name;
private String password;
private int age; public Student(String name, String password) {
this.name = name;
this.password = password;
} public Student(String name, int age) {
this.name = name;
this.age = age;
} @Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}

有两种方式:

1.示例:

<bean id="stu" class="com.chichung.Bean.Student">
<constructor-arg name="name" value="chichung"></constructor-arg>
<constructor-arg name="password" value="123"></constructor-arg>
</bean>

2.示例:

<bean id="stu" class="com.chichung.Bean.Student">
<constructor-arg index="0" value="chichung" type="java.lang.String"></constructor-arg>
<constructor-arg index="1" value="123" type="int"></constructor-arg>
</bean>

  • 加载Spring容器的三种方式

1.类路径获取配置文件(常用)

public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserService userService1 = (UserService) context.getBean("userService");
userService1.add();
}
}

2.文件系统路径获取配置文件

public class Test {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext("/home/chichung/桌面/JavaeePr/MavenTest2/target/classes/beans.xml");
UserService service = (UserService) context.getBean("userService");
service.add();
}
}

3.使用BeanFactory(少用)

public class Test {
public static void main(String[] args) {
BeanFactory BeanFactory = new XmlBeanFactory(new FileSystemResource("/home/chichung/桌面/JavaeePr/MavenTest2/target/classes/beans.xml"));
UserService service = (UserService) BeanFactory.getBean("userService");
service.add();
}
}

注意:

BeanFactory 采取延迟加载,第一次getBean时才会初始化Bean。而ApplicationContext是即时加载的。


  • 装配Bean(xml)的三种方式

1.new 实现类

Bean类:

public class UserServiceImpl implements UserService {

    @Override
public void add() {
System.out.println("业务层");
}
}

xml写法:

<bean id="userService" class="com.chichung.service.impl.UserServiceImpl">
</bean>

2.通过静态工厂创建对象

静态工厂:

public class UserServiceStaticFactory {
public static UserService createUserService(){
return new UserServiceImpl();
}
}

xml写法:

<bean id="userService2" class="com.chichung.factory.UserServiceStaticFactory" factory-method="createUserService">

取得Spring容器的对象:

public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserService service2 = (UserService) context.getBean("userService2");
service2.add();
}
}

3.通过实例工厂创建对象

实例工厂:

public class UserServiceFactory {
public UserService createUserService(){
return new UserServiceImpl();
}
}

xml写法:

<bean id="factory" class="com.chichung.factory.UserServiceFactory"></bean>
<bean id="userService3" factory-bean="factory" factory-method="createUserService"></bean>

取得Spring容器的对象:

public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserService service3 = (UserService) context.getBean("userService3");
service3.add();
}
}

  • Bean的作用域

类别 说明
singleton

在Spring IoC容器中仅存在一个Bean实例,Bean以单例方式存在,默认值

prototype

每次从容器中调用Bean时,都返回一个新的实例,即每次调用getBean()时 ,相当于执行new XxxBean()

request

每次HTTP请求都会创建一个新的Bean,该作用域仅适用于WebApplicationContext环境

session

同一个HTTP Session 共享一个Bean,不同Session使用不同Bean,仅适用于WebApplicationContext 环境

globalSession

一般用于Portlet应用环境,该作用域仅适用于WebApplicationContext 环境

示例:


  • Spring表达式(SpEL)

#{123}、#{'jack'} : 数字、字符串

#{beanId}:另一个bean引用

#{beanId.propName}:操作数据

#{beanId.toString()}:执行方法

#{T(类).字段|方法}:静态方法或字段


  • 集合注入

1.List

2. Set

3.Map

4.Properties

5.数组


  • 反转控制(注解方式)

使用注解方式需要先开启注解。

beans.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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解-->
<context:annotation-config></context:annotation-config>
<!--注解的位置-->
<context:component-scan base-package="com.chichung.Bean"></context:component-scan>
</beans>

1.@Component可以取代<bean class="">

示例:

bean.java

@Component
public class Student {
...
}

test.java

public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = context.getBean(Student.class);
System.out.println(student);
}
}

2.@Component("[id]")可以取代<bean id="" class="">

bean.java

@Component("stu")
public class Student {
...
}

test.java

public class Test1 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("stu");
System.out.println(student);
}
}

3.对于web开发的三层架构,提供了@Respository、@Service、@Controller快速使用。

4.除了@Autowired,还可以用@Qualifier("")或者@Resource("")指定自动注入的名字

5.注解设置Bean的作用域@Scope

Spring框架的基本使用(IOC部分)的更多相关文章

  1. Java开发工程师(Web方向) - 04.Spring框架 - 第2章.IoC容器

    第2章.IoC容器 IoC容器概述 abstract: 介绍IoC和bean的用处和使用 IoC容器处于整个Spring框架中比较核心的位置:Core Container: Beans, Core, ...

  2. 码农小汪-spring框架学习之2-spring IoC and Beans 控制反转 依赖注入 ApplicationContext BeanFactory

    spring Ioc依赖注入控制反转 事实上这个东西很好理解的,并非那么的复杂. 当某个Java对象,须要调用还有一个Java对象的时候(被依赖的对象)的方法时.曾经我们的做法是怎么做呢?主动的去创建 ...

  3. Spring框架知识梳理(一) IOC

    1 写在前面 Spring框架是在大一的时候学习的,但是经过几个项目下来发现自己只不过会用某些常用的东西,对于Spring家族,虽然现在大都使用Spring Boot开发,但是我发现Spring框架的 ...

  4. 10 Spring框架--基于注解的IOC配置

    1.工程环境搭建 2.基于注解的IOC配置 IOC注解的分类 (1)用于创建对象的 他们的作用就和在XML配置文件中编写一个<bean>标签实现的功能是一样的@Component: 作用: ...

  5. spring框架详解: IOC装配Bean

    1 Spring框架Bean实例化的方式: 提供了三种方式实例化Bean. 构造方法实例化:(默认无参数) 静态工厂实例化: 实例工厂实例化: 无参数构造方法的实例化: <!-- 默认情况下使用 ...

  6. Spring框架之什么是IOC的功能?

    1. 什么是IOC的功能? * IoC -- Inverse of Control,控制反转,将对象的创建权反转给Spring!! * 使用IOC可以解决的程序耦合性高的问题!!  

  7. Spring框架之IOC(控制反转)

    [TOC] 第一章Spring框架简介 IOC(控制反转)和AOP(面向方面编程)作为Spring框架的两个核心,很好地实现了解耦合.所以,简单来说,Spring是一个轻量级的控制反转(IoC)和面向 ...

  8. Spring框架的IOC(控制反转)

    1.1.IoC是什么 Ioc-Inversion of Control,即"控制反转",不是什么技术,而是一种设计思想.在Java开发中,Ioc意味着将你设计好的对象交给容器控制, ...

  9. Spring Framework 5.0.0.M3中文文档 翻译记录 Part I. Spring框架概览1-2.2

    Part I. Spring框架概览 The Spring Framework is a lightweight solution and a potential one-stop-shop for ...

  10. 【SSH进阶之路】一步步重构容器实现Spring框架——彻底封装,实现简单灵活的Spring框架(十一)

    文件夹      [SSH进阶之路]一步步重构容器实现Spring框架--从一个简单的容器開始(八)      [SSH进阶之路]一步步重构容器实现Spring框架--解决容器对组件的"侵入 ...

随机推荐

  1. BZOJ4732. [清华集训2016]数据交互(树链剖分+线段树+multiset)

    题目链接 https://www.lydsy.com/JudgeOnline/problem.php?id=4732 题解 首先,一个比较显然的结论是:对于一棵有根树上的两条链 \((x_1, y_1 ...

  2. python学习(十九)常见的第三方库

    原文链接:http://www.limerence2017.com/2017/12/28/python19/#more 介绍几个python中常见的第三方库. Pillow Pillow简称PIL,是 ...

  3. ElasticStack系列之七 & IK自动热更新原理与实现

    一.热更新原理 elasticsearch开启加载外部词典功功能后,会每60s间隔进行刷新字典.具体原理代码如下所示: public void loadDic(HttpServletRequest r ...

  4. vue的全局指令

    vue有四个全局指令:directive.extent.set.component directive:自定义指令 //写一个改变颜色的指令 Vue.directive('amie',function ...

  5. openstack中的server

    一.HTTP server 主要是horizon模块,horizon是基于Python Django搭建的web应用,其运行于Apache网络服务器上(当然也可以运行在其他web服务器上),主要功能就 ...

  6. uboot常用命令详解

    dnw:在进入系统之前进入指令行,输入该指令可下载烧录文件. re:重新启动嵌入式系统. printenv:打印当前系统环境变量. setenv:设置环境变量,格式:setenv name value ...

  7. 在 iPad 上试验从用算法生成法线贴图-到法线映射光照效果

    在 iPad 上试验从用算法生成法线贴图-到法线映射光照效果 目录 概述 一般来说, 法线贴图是用高模的法线图, 低模的纹理图, 来生成较好的渲染效果. 而法线图通常是通过图像处理软件来生成的, 这里 ...

  8. Spring容器事件、自定义事件

    Spring容器内置事件,如容器的启动.停止.关闭.销毁等事件 <bean name="contextStartedHandler" class="com.nuts ...

  9. jquery bxslider幻灯片样式改造

    找了很多jquery的幻灯片,都觉得不是很好,最后发现bxslider兼容性最好,移动设备支持手动翻动. 但是官方提供的显示效果真的很难看,让人难以接受.最后只能自己DIY了. bxslider官方样 ...

  10. 选择Memcached还是Redis?

    两者相似之处 Memcached与Redis都属于内存内.键值数据存储方案.它们都从属于数据管理解决方案中的NoSQL家族,而且都基于同样的键值数据模型.双方都选择将全部数据保存在内存当中,这自然也就 ...