Spring学习-----ONE

来源:互联网 发布:对p2p网络信贷的看法 编辑:程序博客网 时间:2024/06/08 04:44

Spring是分层的JavaSE/EE一站式轻量级框架。
1、 一站式:

  • web层:SpringMVC
  • 持久层:JDBC Template
  • 业务层:Spring的Bean管理

2、 Spring核心:

  • IOC:反转控制—–将对象的创建权交友Spring完成。
  • AOP:面向切面编程。

3、 Spring的优点:

  • 方便解耦,简化开发

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

  • AOP编程的支持

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

  • 声明式事务的支持

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

  • 方便程序的测试

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

  • 方便集成各种框架

Spring不排斥各种优秀的框架,其内部提供了对各种优秀框架的直接支持。

  • 降低JavaEE API的使用难度

Spring对JavaEE开发中非常难用的一些API都提供了封装,使这些API应用难度大大降低。

Spring入门

  • 配置Spring环境
    • 导入jar包
      • 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
      • com.springsource.org.apache.log4j-1.2.15.jar
    • 创建Spring的配置文件
      文件名可以自己指定,但是一般使用applicationContext.xml
      • 为配置文件引入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“>
        </beans>

开始入门程序

创建User类,提供getter/setter方法。

  1. 传统方法中使用User
    这里写图片描述
  2. Spring方式使用User
    这里写图片描述
    我们可以不使用setName(“Tom”)方法为user的name赋值。—–依赖注入(Dependency Injection)
    在配置文件中进行配置:
    这里写图片描述

IOC和DI的区别?
IOC:控制反转,将对象的创建权交给Spring管理。
DI:依赖注入,在Spring创建对象的过程中把对象依赖的属性注入到类中。

Spring框架加载applicationContext.xml文件的方式:
加载classpath下的配置文件:
new ClassPathXmlApplicationContext(“applicationContext.xml”);
加载磁盘路径下的配置文件:
new FileSystemXmlApplicationContext(“applicationContext.xml”);

BeanFactory与ApplicationContext区别?
答:ApplicationContext类继承了BeanFactory.
BeanFactory在使用到这个类的时候,getBean()方法的时候才会加载这个类。
ApplicationContext类加载配置文件的时候创建所有的类。
ApplicationContext对BeanFactory提供了扩展:
1、国际化处理;
2、事件传递;
3、Bean自动装配;
4、各种不同应用层的Context实现。


IOC装配Bean

Spring框架实例化Bean的方式

三种实例化Bean的方法:
1、无参构造方法实例化Bean
这里写图片描述
2、静态工厂实例化Bean
这里写图片描述
3、实例工厂实例化Bean
这里写图片描述

Bean标签中的属性
  • id和name的区别

id遵守XML约束的id约束,id约束保证这个属性的值是唯一的,而且必须以字母开始,可以使用字母、数字、连字符、下划线、句号、冒号。
name没有这些要求。
如果Bean的名称中含有特殊字符,就需要使用name属性。
例如:<bean name=”#person” class=”xxx”/>
由于name属性可以相同,所以后出现的Bean会覆盖之前出现的同名Bean

  • scpoe—–类的作用范围

这里写图片描述
测试singleton属性值:
这里写图片描述
这里写图片描述
创建两个对象比较为true,说明只生成了一个实例。

测试prototype属性值:
这里写图片描述
这里写图片描述
创建两个对象比较为false,说明只生成了多个实例。

Bean的生命周期

配置Bean的初始化和销毁的方法:
init-method=”setup”
destory-method=”teardown”
执行销毁的时候必须收到关闭工厂,而且只对scope=singleton有效。
测试初始化和销毁:
在User类中添加setup()和teardown()方法:
这里写图片描述
这里写图片描述
测试:
这里写图片描述
结果:
这里写图片描述

Bean的生命周期的11个步骤:
1、对象的初始化
2、封装属性
3、如果Bean实现BeanNameAware执行setBeanName
4、如果Bean实现BeanFactoryAware 或者 ApplicationContextAware, 设置工厂 setBeanFactory 或者 上下文对象setApplicationContext
5、如果存在类实现 BeanPostProcessor (后处理Bean),执行postProcessBeforeInitalization
6、如果Bean实现InitalizingBean,执行afterPropertiesSet
7、调用<bean init-method=”init”>指定初始化方法
8、如果存在类实现 BeanPostProcessor (处理Bean),执行postProcessAfterInitalization
9、执行业务处理
10、如果Bean实现DisposableBean执行destory
11、调用<bean destory-method=”customerDestory”>指定销毁方法customerDestory.

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

创建CustomerService接口:

public interface CustomerService {    public void add();    public void find();}

实现CustomerService接口创建实现类:

import org.springframework.beans.BeansException;import org.springframework.beans.factory.BeanNameAware;import org.springframework.beans.factory.DisposableBean;import org.springframework.beans.factory.InitializingBean;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;public class CustomerServiceImpl implements CustomerService ,BeanNameAware,ApplicationContextAware,InitializingBean,DisposableBean{    private String name;    public void setName(String name) {        System.out.println("第二步:属性的注入.");        this.name = name;    }    public CustomerServiceImpl() {        super();        System.out.println("第一步:实例化类.");    }    public void add() {        System.out.println("add()方法...");    }    public void find() {        System.out.println("find()方法...");    }    public void setBeanName(String beanName) {        System.out.println("第三步,setBean注入配置的类的名称"+beanName);    }    public void setApplicationContext(ApplicationContext context)            throws BeansException {        System.out.println("第四步,设置工厂"+context);    }    public void afterPropertiesSet() throws Exception {        System.out.println("第六步,属性设置后执行...");    }    public void init(){        System.out.println("第七步,初始化方法...");    }    public void destroy() throws Exception {        System.out.println("第十步,执行destory方法...");    }    public void teardown(){        System.out.println("第十一步:调用手动销毁方法...");    }}

创建MyBeanPostProcessor实现BeanPostProcessor:

import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.BeanPostProcessor;public class MyBeanPostProcessor implements BeanPostProcessor {    public Object postProcessAfterInitialization(final Object bean, String beanName)            throws BeansException {        System.out.println("第八步:初始化之后执行...");        //动态代理        if("customerService".equals(beanName)){            Object proxy = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler(){                public Object invoke(Object proxy, Method method, Object[] args)                        throws Throwable {                    if("add".equals(method.getName())){//如果是add方法,我们才进行校验                        System.out.println("权限校验...");                        Object result = method.invoke(bean, args);                        return result;                    }                    return method.invoke(bean, args);                }            });            return proxy;        }        return bean;    }    public Object postProcessBeforeInitialization(Object bean, String beanName)            throws BeansException {        System.out.println("第五步:初始化之前执行...");        return bean;    }}

配置配置文件:
这里写图片描述

运行:
这里写图片描述
结果:
这里写图片描述
如我们所愿,只对add()方法进行权限校验。


Bean中属性的注入

Spring框架支持构造方法注入和setter方法注入。

构造方法注入

这里写图片描述

setter方法注入

这里写图片描述
使用setter方法注入时一定要有默认的无参构造函数,不然会报错
这里写图片描述

名称空间p:注入属性

在applicationContext.xml约束中引入名称空间p:
xmlns:p=”“http://www.springframework.org/schema/p”
这里写图片描述

SpEL:属性的注入

语法:#{表达式}
<bean id=”” value=”#{表达式}”/>
这里写图片描述

集合属性的注入

List集合的注入:
这里写图片描述
Map集合的注入:
这里写图片描述

多个配置文件的加载

一种写法:
这里写图片描述
另外一种写法:
这里写图片描述
在配置文件1中导入配置文件2.


(注解方式)IOC装配Bean

使用准备:
引入xml约束:
xmlns:context=”http://www.springframework.org/schema/context”
在xsi:schemaLocation中添加:
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

配置自动扫描的包:
这里写图片描述

使用注解装配Bean
  • @Component:描述Spring框架中的Bean
  • @Repository:用于对DAO实现类进行标注
  • @Service:用于对Service实现类进行标注
  • @Controller:用于对控制器实现类进行标注
使用注解进行属性注入

普通属性:
使用@Value注解进行属性的注入:
这里写图片描述
这里写图片描述

对象属性:
@Autowired:自动装配默认使用类型注入。
如果存在两个相同Bean类型,则按照名称注入
@Qualifier:指定注入Bean名称。
通过设置@Autowired注解的required属性为true,设置一定要找到匹配的Bean。
@Resource注解和@Autowired注解功能类似。
@Autowired
@Qualifier(“userDao”)
等价于
@Resource(name=”userDao”)

Bean其他属性配置

配置初始化方法和销毁方法:
@PostConstruct初始化
@PreDestory销毁
配置Bean作用范围:
@Scope()

以JavaConfig为核心提供使用java类定义Bean信息的方法

@Configuration:指定POJO类为Spring提供Bean定义信息。
@Bean:提供一个Bean定义信息。
Spring提供AnnotationConfigApplicationContext用于加载使用@Configuration配置注解工厂类。
这里写图片描述

多种装配方式比较

这里写图片描述

原创粉丝点击