优雅的Spring框架介绍

什么是spring?我这里简单介绍一下:spring是一个一站式的解决框架,提供了开发JAVA应用程序时所需的全面的基础架构,所以你可以把注意力放到程序实现上。

spring的核心是控制反转(IoC)、依赖注入(DI)面向切面(AOP)

spring的优点:

* 轻量级的容器框架,没有侵入性
* IoC更加容易组合对象之间的关系,通过面向接口进行编程,可以低耦合开发。
* 易于本地测试(Junit单元测试,不用部署服务器)
* AOP可以更加容易的进行功能扩展,遵循OCP开发原则。
* Spring默认对象的创建为单例的,我们不需要再使用单例的设计模式来开发单体类。
* Spring的集成很强大,另外可以对其他框架的配置进行一元化管理。
* Spring的声明式事务的方便使用

IoC: inversion of controller ,把创建对象的控制权利反转交给了spring,这一过程叫做控制反转(就是通过反射创建对象的过程)

首先要想用spring,第一步肯定就是导包咯。spring有 4 + 1 : 4个核心(beans、core、context、expression) + 1个依赖(commons-loggins…jar)这里我用maven来加入这些依赖,没用maven的手动导入这些jar包就可以了!
maven的配置文件 pom.xml 如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.yida.spring</groupId>
  <artifactId>spring01</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

    <dependencies>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.2.4.RELEASE</version>
</dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>4.2.4.RELEASE</version>
</dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>4.2.4.RELEASE</version>
</dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-expression</artifactId>
    <version>4.2.4.RELEASE</version>
</dependency>

  <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.2.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>

</dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>4.2.4.RELEASE</version>
</dependency>

  </dependencies>

  <build>  
    <plugins>  
        <plugin>  
            <groupId>org.apache.maven.plugins</groupId>  
            <artifactId>maven-compiler-plugin</artifactId>  
            <configuration>  
                <source>1.8</source>
                <target>1.8</target>  
            </configuration>  
        </plugin>  
    </plugins>  
</build>
</project>

入门案例 :创建一个接口UserService

public interface UserService {
    void sayHello();
}

以及接口的实现类UserServiceImpl:

public class UserServiceImpl implements UserService{
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void sayHello() {
        System.out.println("hello spring"+name);
    }

}

applicationContext.xml配置如下:

<bean id="UserServiceImpl" class="com.yida.spring.demo01.UserServiceImpl">
    <property name="name" value="zhoujie"></property>
</bean>

测试用例:

@Test
    public void test01(){
        //获取spring容器
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserServiceImpl userservice = (UserServiceImpl) context.getBean("UserServiceImpl");
        userservice.sayHello();//结果:hello springzhoujie
    }

接下来测试通过静态工厂的方式来创建对象:
首先我们有一个生产静态工厂的方法 MyStaticFactory

public class MyStaticFactory {
    public static SayHelloFactoryClass getMyFactory(){
        return new SayHelloFactoryClass();
    }
}

具体的方法SayHelloFactoryClass

public class SayHelloFactoryClass {
    public void sayHello(){
        System.out.println("hello static myfactory class");
    }
}

applicationContext.xml配置如下:

<!-- 静态工厂创建对象 -->
<bean id="MyStaticFactory" class="com.yida.spring.demo02.MyStaticFactory" factory-method="getMyFactory"></bean>

测试用例:

/**
     * 测试静态工厂的方式创建对象
     */
    @Test
    public void test02(){
         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
         SayHelloFactoryClass sayHello = (SayHelloFactoryClass) context.getBean("MyStaticFactory");
         sayHello.sayHello();//结果:hello static myfactory class
    }

实例工厂的方式来创建对象:
有一个实例工厂类MyInstanceFactory:

public class MyInstanceFactory {
    public MyInstanceFactoryClass getMyInstance(){
        return new MyInstanceFactoryClass();
    }
}

具体的方法为MyInstanceFactoryClass

public class MyInstanceFactoryClass {
    public void sayHello(){
        System.out.println("hello my instance factory");
    }
}

applicationContext.xml配置如下:

<!-- 实例工厂创建对象 -->
<bean id="MyInstanceFactory" class="com.yida.spring.demo02.MyInstanceFactory"></bean>
<bean id="MyInstanceFactoryClass" class="com.yida.spring.demo02.MyInstanceFactoryClass" factory-bean="MyInstanceFactory"

测试用例:

/**
     * 通过实例 工厂创建对象
     */
    @Test
    public void test03(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        MyInstanceFactoryClass myIns = (MyInstanceFactoryClass) context.getBean("MyInstanceFactoryClass");
        myIns.sayHello();//hello my instance factory
    }

spring对象的生命周期:
目标类BeanLife如下:

public class BeanLife {
    /**
     * 指定初始化方法
     */
    public void initMethod(){
        System.out.println("我是初始化方法,我在创建对象的时候就会被调用");
    }
    public void sayHello(){
        System.out.println("hello  bean  life  ");

    }
    /**
     * 指定销毁方法
     */
    public void destroyMehtod(){
        System.out.println("我是关闭方法,只有在容器关闭的时候,我才会被调用");
    }

}

applicationContext.xml配置如下:

<!-- spring对象的生命周期 -->
  <bean id="beanLife" class="cn.itcast.spring.demo3.BeanLife" init-method="initMethod" destroy-method="destroyMehtod"></bean>

测试用例:

/**
     * spring容器创建对象的生命周期
     */

    @Test
    public void getBeanLife() throws Exception {
        //获取容器
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        BeanLife bean = (BeanLife) context.getBean("beanLife");
        bean.sayHello();
        context.close();
    }

运行结果:
我是初始化方法,我在创建对象的时候就会被调用
hello bean life
我是关闭方法,只有在容器关闭的时候,我才会被调用

以上只是做了一个spring的基本用法介绍,spring的依赖注入这里 就不做过多的介绍了,那么说一下spring与web的整合吧。通过以上介绍我们知道,再拿对象的时候通过spring容器我们已经不需要用一次就new一次了,这样大大节省了内存,那么问题 来了,我们每次创建容器的时候都需要new,很麻烦,也很浪费内存。那么我们可不可以在我们的Tomcat服务器一启动的时候就创建我们的容器,然后就保证我们的容器不会被销毁呢?
办法是有的。我们的应用一启动就会去加载一个servletContext对象,直到我们的Tomcat停止为止! 那么我们可以写一个监听器,来监听servletContext的启动(顺便提一下Javaweb的三大组件:servlet、filter、listener),servletContext一启动就马上启动spring的容器 ,spring的容器启动成功后就将spring容器丢到servletContext里面,以后每次用就直接从servletContext中获取即可,ok完成!注意这个过程已经有人帮我们写好了,我们不用自己写,虽然你自己写也是可以的。只需导入spring-web的包就可以了,前面一开始的时候我已经放在pom.xml里面了。然后在WEB-INF里的web.xml里配置监听器如下:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

创建servlet测试:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        ServletContext servletContext = request.getServletContext();
        WebApplicationContext applicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        System.out.println(applicationContext);
        SayHelloFactoryClass bean = (SayHelloFactoryClass) applicationContext.getBean("MyStaticFactory");
        bean.sayHello();
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

这里调用的是静态工厂方法,spring与web的整合已经完成!

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值