Java框架:Spring原理与环境搭建

来源:互联网 发布:java单例模式调用 编辑:程序博客网 时间:2024/05/23 19:15

Spring是基于IOC和AOP的J2EE系统的框架。
IOC(Inversion Of Control) 反转控制
— 创建对象由以前的程序员自己new构造方法来调用,变成了交由Spring创建对象
DI(Dependency Inject)依赖注入
— 拿到对象的属性,已经被注入好相关值,直接使用即可。

项目搭建

新建spring普通Java项目并导入jar包

这里写图片描述

把jar包导入到项目中,导包办法:右键 project->properties->java build path->libaries->add external jars

准备POJO(Plain Old Java Objects)

package com.neu.pojo;public class Category {    private int id;    private String name;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

准备applicationContext.xml

spring 核心配置文件,放到src目录下

<?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:aop="http://www.springframework.org/schema/aop"    xmlns:tx="http://www.springframework.org/schema/tx"     xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="   http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   http://www.springframework.org/schema/aop    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   http://www.springframework.org/schema/tx    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.0.xsd">    <bean name="c" class="com.neu.pojo.Category">        <property name="name" value="asce tech" />    </bean></beans>

其中,

    <bean name="c" class="com.neu.pojo.Category">        <property name="name" value="asce tech" />    </bean>

通过关键字c 即可获取Category 对象,并注入字符串“asce tech”到name属性中。

TestSpring

通过spring获取Category对象,以及该对象被注入的name属性

package com.neu.test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.neu.pojo.Category;public class TestSpring {    public static void main(String[] args) {        ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });        Category c = (Category) context.getBean("c");        System.out.println(c.getName());    }}

获取对象方式的区别

传统方式

通过new关键字主动创建一个对象

IOC方式

对象的生命周期由Spring来管理,直接从Spring获取一个对象。(控制权交给Spring)


注入对象

对Product对象,注入一个Category对象

准备Product类

package com.neu.pojo;public class Product {    private int id;    private String name;    private Category category;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Category getCategory() {        return category;    }    public void setCategory(Category category) {        this.category = category;    }}

修改applicationContext.xml

使用ref 来注入另一个对象。

    <bean name="c" class="com.neu.pojo.Category">        <property name="name" value="asce tech" />    </bean>    <bean name="p" class="com.neu.pojo.Product">        <property name="name" value="product asce"/>        <property name="category" ref="c" />    </bean>

TestSping

在之前的TestSpring中添加

        Product p = (Product) context.getBean("p");        System.out.println(p.getName());        System.out.println(p.getCategory().getName());

注解方式IOC/DI

修改applicationContext.xml

添加<context:annotation-config/>
注释掉注入对象的ref行

    <context:annotation-config/>    <bean name="c" class="com.neu.pojo.Category">        <property name="name" value="asce tech" />    </bean>    <bean name="p" class="com.neu.pojo.Product">        <property name="name" value="product asce"/>    <!-- <property name="category" ref="c" />-->    </bean>

@Autowired注解

在Product类的Category属性前加上@Autowired注解

import org.springframework.beans.factory.annotation.Autowired;    private int id;    private String name;    @Autowired    private Category category;

运行同样成功。

也可在setCategory方法前加上@Autowired,实现同样效果

@Autowiredpublic void setCategory(Category category)

此外,除@Autowired还可使用@Resource注解

import javax.annotation.Resource;    @Resource(name="c")    private Category category;

@Component注解

修改applicationContext.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:aop="http://www.springframework.org/schema/aop"    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="   http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   http://www.springframework.org/schema/aop    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   http://www.springframework.org/schema/tx    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.0.xsd">    <context:component-scan base-package="com.neu.pojo"/></beans>

告知spring,bean都放在com.neu.pojo包中。

为实体类加上@Component注解

为实体类添加@Component注解,并将属性初始化放在属性声明上进行。

package com.neu.pojo;import org.springframework.stereotype.Component;@Componentpublic class Category {    private int id;    private String name = "asce tech";    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}
package com.neu.pojo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Componentpublic class Product {    private int id;    private String name = "product asce";    @Autowired    private Category category;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    .......}

运行TestSpring结果相同。


AOP

AOP, Aspect Oriental Pragram 面向切面编程
面向切面编程,将功能分为核心业务功能,辅助功能。
比如登陆,增加数据,删除数据都叫核心业务
辅助功能,比如性能统计,日志,事务管理等等

辅助功能在Spring的面向切面编程AOP思想中,称为切面。
核心业务功能和切面业务功能分别独立开发,然后能够选择性的,低耦合的把切面功能和核心业务功能编织在一起即为AOP.

准备

业务类ProductService

package com.neu.service;public class ProductService {    public void doSomeService(){        System.out.println("dosomeservice");    }}

TestString

package com.neu.test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.neu.service.ProductService;public class TestSpring {    public static void main(String[] args) {        ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });        ProductService s = (ProductService) context.getBean("s");        s.doSomeService();    }}

准备日志切面 LoggerAspect

该日志切面的功能是 在调用核心功能之前和之后分别打印日志。

package com.neu.aspect;import org.aspectj.lang.ProceedingJoinPoint;public class LoggerAspect {    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {        System.out.println("start log:" + joinPoint.getSignature().getName());        Object object = joinPoint.proceed();        System.out.println("end log:" + joinPoint.getSignature().getName());        return object;    }}

修改applicationContext.xml

    <bean name="s" class="com.neu.service.ProductService"></bean>    <bean id="loggerAspect" class="com.neu.aspect.LoggerAspect" />    <aop:config>        <aop:pointcut expression="execution(* com.neu.service.ProductService.*(..))"            id="loggerCutpoint" />        <aop:aspect id="logAspect" ref="loggerAspect">            <aop:around pointcut-ref="loggerCutpoint" method="log" />        </aop:aspect>    </aop:config>

解释:
声明核心业务对象

<bean name="s" class="com.neu.service.ProductService"></bean>

声明日志切面

<bean id="loggerAspect" class="com.neu.aspect.LoggerAspect" />

指定核心业务功能

<aop:pointcut id="loggerCutpoint"            expression="execution(* com.neu.service.ProductService.*(..)) " />

指定辅助功能

<aop:aspect id="logAspect" ref="loggerAspect">    <aop:around pointcut-ref="loggerCutpoint" method="log" /></aop:aspect>

然后通过aop:config把业务对象与辅助功能编织在一起。

execution(* com.neu.service.ProductService.*(..)) 

* 表示任意类型,
com.neu.service.ProductService.*(..)) 以com.neu.service.ProductService 开头的类的任意方法
(..) 参数是任意数量和类型。

运行结果

start log:doSomeServicedosomeserviceend log:doSomeService

注解方式AOP

注解配置业务类

package com.neu.service;import org.springframework.stereotype.Component;@Component("s")public class ProductService {    public void doSomeService(){        System.out.println("dosomeservice");    }}

注解配置切面

@Aspect注解—表示一个切面
@Component—表示一个bean,由Spring进行管理
@Around(value=”execution(* com.neu.service.ProductService.*(..))”)—表示对com.neu.service.ProductService这个类中的所有方法进行切面操作。

package com.neu.aspect;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.springframework.stereotype.Component;@Aspect@Componentpublic class LoggerAspect {    @Around(value="execution(* com.neu.service.ProductService.*(..))")    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {        System.out.println("start log:" + joinPoint.getSignature().getName());        Object object = joinPoint.proceed();        System.out.println("end log:" + joinPoint.getSignature().getName());        return object;    }}

修改applicationContext.xml

    <context:component-scan base-package="com.neu.aspect"></context:component-scan>    <context:component-scan base-package="com.neu.service"></context:component-scan>    <aop:aspectj-autoproxy/> 

注解方式测试

注解方式用到junit,导入junit-4.12.jar和hamcrest-all-1.3.jar

TestSpring

package com.neu.test;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.neu.pojo.Category;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class TestSpring {    @Autowired    Category c;    @Test    public void test(){        System.out.println(c.getName());    }}

解释

@RunWith(SpringJUnit4ClassRunner.class) 

表示Spring测试类

@ContextConfiguration("classpath:applicationContext.xml")

定位Spring的配置文件

@Autowired

给这个测试类装配Category对象

@Test

测试逻辑,打印c对象的名称。


参考:
http://how2j.cn/k/tmall-j2ee/tmall-j2ee-894/894.html?p=4066 一个非常好的网站,里面有几个实用的项目,推荐一个。

0 0
原创粉丝点击