1.前期准備
(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文件夾下面
(2)做一個測試類
實體類Person:
package com.demo;
public class Person {
public String say(){
return "說了一句話:哇哈哈哈哈~";
}
}
測試類:
package com.demo;
import org.junit.Test;
public class Test01 {
@Test
public void test() {
Person p =new Person();
System.out.println(p.say());
}
}
項目的文件結構如下
2.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定義這個文件
<?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測試了,內容如下:
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框架就弄好了。
3.新建一個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>");
}
這時候輸入地址,就會出現想要的結果:
4.用注釋注入依賴
(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:
1、基於xml配置Bean
2、使用注解定義Bean
(@Component、@Controller、@Service、@Repository)
3、基於javaConfig提供Bean定義信息(@Configuration、@Bean)
5.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的參數名必須與配置文件中的<aop:after-returning returning="result"/>中的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