搭建一個超級簡單的spring框架

1.準備環境

(1)下載JDK、myEclipse、Tomcat,以後配置好相關的參數

備註:在myEclipse上配置Tomcat:



啓動Tomcat服務後,在瀏覽器輸入localhost:8080運行成功即表示配置成功html

(2)新建一個Web Project


配置到Tomcat上

再次啓動Tomcat,輸入地址後,若是能運行成功即表示新建成功
java

2.前期準備

(1)首先下載所須要的jar包

下載地址:
spring-framework-4.0.4.RELEASE-dist:http://repo.springsource.org/libs-release-local/org/springframework/spring/4.0.4.RELEASE/
commons-logging-1.1.3-bin:http://commons.apache.org
其餘諸如log4j之類的並非必須下載的。
若是下載速度慢能夠在國內網站下載。
附:
spring-4.3.13-all:
連接:https://pan.baidu.com/s/1tUUzKOkVLbkJD7jZukM1hg 提取碼:v2zc
commons-logging-1.2-bin:
連接:https://pan.baidu.com/s/1CdYp9ozTH-zVStaTw5WI1g 提取碼:1ixb
下載後得到的jar包放在lib文件夾下面
web

(2)作一個測試類

實體類Person:spring

package com.demo;

public class Person {
    public String say(){
        return "說了一句話:哇哈哈哈哈~";
    }

}

測試類:express

package com.demo;

import org.junit.Test;

public class Test01 {

    @Test
    public void test() {
        Person p =new Person();
        System.out.println(p.say());
    }

}

項目的文件結構以下
apache

3.spring的最簡單的應用

在上圖位置新建一個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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="person" class="com.demo.Person"></bean>
</beans>

以後在web.xml定義這個文件tomcat

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name></display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:resource/applicationContext.xml</param-value>
    </context-param>
    
</web-app>

作好聲明處理以後,就能夠在測試類Test測試了,內容以下:app

package com.demo;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test01 {

    @Test
    public void test() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("resource/applicationContext.xml");
        Person p = (Person) ctx.getBean("person", Person.class);
        System.out.println(p.say());
    }

}

測試成功後,這樣,最簡單的spring框架就弄好了。框架

4.新建一個Servlet類

(1)具體步驟以下:


(2)新建完後的變化:


新建完,在web.xml會自動添加如下配置:

<servlet>
    <servlet-name>IndexServlet</servlet-name>
    <servlet-class>com.servlet.IndexServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>IndexServlet</servlet-name>
    <url-pattern>/IndexServlet</url-pattern>
  </servlet-mapping>

(3)測試代碼

在IndexServlet類下,修改以下代碼:

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        ApplicationContext ctx = new ClassPathXmlApplicationContext("resource/applicationContext.xml");
        Person p = (Person) ctx.getBean("person", Person.class);
        
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><head><title>一二零叄的網站</title></head><body>");
        out.print(p.say()+"</body></html>");
        
    }

這時候輸入地址,就會出現想要的結果:

5.用註釋注入依賴

(1)準備工做:須要導入的一個包:

spring-aop-4.3.13.RELEASE.jar

(2)準備工做:導完包後修改一下配置文件

配置信息以下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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
          http://www.springframework.org/schema/context 
          http://www.springframework.org/schema/context/spring-context.xsd">
          
      <context:component-scan base-package="com.entity"></context:component-scan>
      
      <bean id="person1" class="com.entity.Person"></bean>
    
</beans>

備註:
開啓註解掃描有兩種配置:

<context:component-scan base-package= ""/>
<context:annotation-config/>

區別是:
a.兩種配置都能開啓註解掃描,這樣就可使用@Component、@Autowired這些註解了。
b.<context:component-scan base-package= 「」/>會到指定包(包括指定包下的全部子包)中掃描類、方法、屬性上面是否有註解。(若有多個,可以使用逗號分隔)
<context:annotation-config></context:annotation-config>這個配置只掃描屬性上是否有註解,因此通常不用寫。

(3)使用註釋注入依賴

package com.entity;

import org.springframework.stereotype.Component;

@Component("person2")
public class Person {
    
    private String username;
    private int sex;
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public int getSex() {
        return sex;
    }
    public void setSex(int sex) {
        this.sex = sex;
    }
    public String say(){
        return "說了一句話:哇哈哈哈哈~";
    }
    
}

調用:

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        ApplicationContext ctx = new ClassPathXmlApplicationContext("resource/applicationContext.xml");
        Person p1 = (Person) ctx.getBean("person1");
        p1.setUsername("張三");
        Person p2 = (Person) ctx.getBean("person2");
        p2.setUsername("李四");
        
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><head><title>一二零叄的網站</title></head><body>");
        out.print(p1.getUsername() + p1.say()+"<br/>");
        out.print(p2.getUsername() + p2.say());
        out.print("</body></html>");
        
    }

結果:

這樣,使用xml配置文件和使用註釋來注入依賴就均可以實現了
備註:
Spring容器有三種方式配置Bean:
一、基於xml配置Bean
二、使用註解定義Bean
(@Component、@Controller、@Service、@Repository)
三、基於javaConfig提供Bean定義信息(@Configuration、@Bean)

6.AOP應用

(1)下載所須要的包

aspectj 1.8.10:http://mvnrepository.com/artifact/org.aspectj/aspectjrt/1.8.10
aspectjweaver 1.8.10:http://mvnrepository.com/artifact/org.aspectj/aspectjweaver/1.8.10
aopalliance 1.0:http://mvnrepository.com/artifact/aopalliance/aopalliance/1.0
附:
aopalliance、aspectjrt、aspectjweaver:
連接:https://pan.baidu.com/s/1rp6erh5WUVZsUymsO2b6Ow 提取碼:lm7x

(2)新建一個通知類:

package com.service;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

public class MyAdvice {
    public void beforeMethod(JoinPoint joinpoint) {
        System.out.println("前置通知---");
    }

    public void afterMethod(JoinPoint joinpoint) {
        System.out.println("後置通知---");
    }

    public void afterReturnning(JoinPoint joinpoint, Object result) {
        System.out.println("返回通知---");
    }

    public void afterThrowing(JoinPoint joinpoint, Exception ex) {
        System.out.println("【異常通知】---" + joinpoint.toString());
    }

    public Object aroundMethod(ProceedingJoinPoint pjp) {
        Object obj = null;
        try {
            System.out.println("環繞通知---");
            long start = System.currentTimeMillis();
            obj = pjp.proceed(); // 執行目標方法
            long end = System.currentTimeMillis();
            System.out.println("環繞通知結束---方法執行時間:" + (end - start));
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return obj;
    }
}

注:
JoinPoint:鏈接點(切入點)的鏈接對象,經過它能夠獲取目標對象中的信息。
Object resuldt的參數名必須與配置文件中的 中的returning屬性的值一致。

(3)配置文件修改:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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
          http://www.springframework.org/schema/context 
          http://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/aop 
          http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">

    <context:component-scan base-package="com.entity"></context:component-scan>

    <bean id="person1" class="com.entity.Person"></bean>
    <bean id="makePerson" class="com.service.MakePerson" />
    <bean id="myAdvice" class="com.service.MyAdvice" />

    <!-- aop的配置 -->
    <aop:config>
        <!-- 配置切入點 -->
        <!-- public * *(..) 表示全部public的方法 -->
        <aop:pointcut expression="execution(public * *(..))" id="pointcut" />
        <!-- 配置切面及切入的對象 -->
        <aop:aspect ref="myAdvice">
            <aop:before pointcut-ref="pointcut" method="beforeMethod" />
            <aop:after pointcut-ref="pointcut" method="afterMethod" />
            <aop:after-returning pointcut-ref="pointcut"
                method="afterReturnning" returning="result" />
            <aop:around pointcut-ref="pointcut" method="aroundMethod" />
            <aop:after-throwing pointcut-ref="pointcut"
                method="afterThrowing" throwing="ex" />
        </aop:aspect>
    </aop:config>

</beans>

(4)顯示界面修改

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        ApplicationContext ctx = new ClassPathXmlApplicationContext("resource/applicationContext.xml");
        Person p1 = (Person) ctx.getBean("person1");
        p1.setUsername("張三");
        Person p2 = (Person) ctx.getBean("person2");
        p2.setUsername("李四");
        MakePerson p3 = (MakePerson) ctx.getBean("makePerson");
        
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><head><title>一二零叄的網站</title></head><body>");
        out.print(p1.getUsername() + p1.say()+"<br/>");
        out.print(p2.getUsername() + p2.say()+"<br/>");
        out.print(p3.getNewPerson("王五"));
        out.print("</body></html>");
    }

(5)最終結果


後臺顯示:
這樣,就可以使用spring的注入依賴和麪向切面技術了,一個很簡單的spring框架就搭好了。 附: Spring PPT教程: 連接:https://pan.baidu.com/s/1T6ZJrb9Pbb2_Qmso72trIg 提取碼:x1sn

相關文章
相關標籤/搜索