Spring总结
Spring
1、配置 ---声明JavaBean
第一种:在配置文件中,通过id匹配class来声明javaBean
第二种:在配置文件中,开启注解,设置注解所在的包,在对应的类添加注解
@Controller:控制器注解
@Service:服务层注解
@Repository:DAO层注解
@Component:不好分层的类的注解
2、声明切入点,创建通知
Spring-IOC-0
配置Spring.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- id:是自定义的字符串, class:类的包名加类名 -->
<bean id="people" class="com.share.People">
<!-- 设置注入:在配置文件中,配置成员变量的属性 -->
<!-- <property name="name" value="tangxin" /> <property name="age" value="18"></property>
<property name="addr" ref="addr"></property> -->
<!-- 构造注入:通过构造函数的形式,为成员赋值 -->
<constructor-arg index="0" value="tangxin" />
<constructor-arg index="1" value="20"></constructor-arg>
<constructor-arg index="2" ref="addr"></constructor-arg>
</bean>
<bean id="addr" class="com.share.Addr">
<!-- <property name="pro" value="sichuan"></property> <property name="city"
value="deyang"></property> -->
<constructor-arg index="0" value="sichuan"></constructor-arg>
<constructor-arg index="1" value="deyang"></constructor-arg>
</bean>
<bean id="teacher" class="com.tx.pojo.Teacher">
<property name="name" value="唐鑫" />
<property name="age" value="123" />
</bean>
<bean id="stu" class="com.tx.pojo.Student">
<!-- 设置注入 -->
<property name="id" value="1" />
<property name="name" value="小华" />
<property name="sex" value="女" />
<property name="age" value="20" />
<property name="myTeacher" ref="teacher" />
<!-- 构造注入 -->
<constructor-arg index="0" value="100" />
<constructor-arg index="1" value="王小二" />
<constructor-arg index="2" value="男" />
<constructor-arg index="3" value="30" />
<constructor-arg index="4" ref="teacher" />
</bean>
<bean id="peo" class="com.tx.pojo.People">
<property name="name" value="tangxin"></property>
<property name="sex" value="man"></property>
<!-- 把Scores对象注入到People对象中 -->
<property name="scores" ref="score"></property>
</bean>
<bean id="score" class="com.tx.pojo.Scores">
<property name="math" value="99"></property>
<property name="chinese" value="98"></property>
</bean>
</beans>
pojo类
package com.tx.pojo;
public class People {
private String name;
private String sex;
private Scores scores;
public People(){
}
public People(String name,String sex,Scores scores){
this.name = name;
this.sex= sex;
this.scores = scores;
}
public Scores getScores() {
return scores;
}
public void setScores(Scores scores) {
this.scores = scores;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getsex() {
return sex;
}
public void setsex(String sex) {
this.sex = sex;
}
}
package com.tx.pojo;
public class Teacher {
private String name;
private String age;
public Teacher(){
}
public Teacher(String name,String age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
package com.tx.pojo;
public class Student {
private String id;
private String name;
private String sex;
private String age;
private Teacher myTeacher;
public Student() {
// TODO Auto-generated constructor stub
}
public Student(String id,String name,String sex,String age,Teacher myTeacher){
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
this.myTeacher = myTeacher;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Teacher getMyTeacher() {
return myTeacher;
}
public void setMyTeacher(Teacher myTeacher) {
this.myTeacher = myTeacher;
}
}
package com.tx.pojo;
public class Scores {
private String math;
private String chinese;
public Scores() {
// TODO Auto-generated constructor stub
}
public Scores(String math,String chinese){
this.math = math;
this.chinese = chinese;
}
public String getMath() {
return math;
}
public void setMath(String math) {
this.math = math;
}
public String getChinese() {
return chinese;
}
public void setChinese(String chinese) {
this.chinese = chinese;
}
}
package com.tx.pojo;
public class Person {
private String name;
private String age;
public Person(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
------
package com.share;
public class Addr {
private String pro;
private String city;
public Addr() {
// TODO Auto-generated constructor stub
}
public Addr(String pro, String city) {
this.pro = pro;
this.city = city;
}
public String getPro() {
return pro;
}
public void setPro(String pro) {
this.pro = pro;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
package com.share;
public class People {
private String name;
private int age;
private Addr addr;
public People() {
// TODO Auto-generated constructor stub
}
public People(String name, int age, Addr addr) {
this.name = name;
this.age = age;
this.addr = addr;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Addr getAddr() {
return addr;
}
public void setAddr(Addr addr) {
this.addr = addr;
}
}
package com.share;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tx.pojo.Student;
import com.tx.pojo.Teacher;
import java.lang.reflect.Method;
public class UserPeople {
public static void main(String[] args) throws Exception {
//读取Spring的配置文件
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("config/spring.xml");
//从配置文件中,获取people对应的Bean对象(People类对象)
People p = (People) context.getBean("people");
System.out.println(p.getAge() + "====" + p.getName());
System.out.println(p.getAddr().getCity() + "===" + p.getAddr().getPro());
Class clazz = Class.forName("com.share.People");//加载people这个类
Object obj = clazz.newInstance();//通过刚刚加载的class,获取一个People实例
//name --> Name ---> setName (setName)
//age ----> Age ----> setAge (getAge)
Method setN = clazz.getMethod("setName", String.class);//通过加载后class,获得一个带一个String类型参数的方法
setN.invoke(obj, "tangxin");//方法对象执行方法,指定这个方法在那个对象里面====>obj.setName("tangxin");
Method getN = clazz.getMethod("getName", null);
String name = (String) getN.invoke(obj, null);
System.out.println(name);
com.tx.pojo.People p1 = (com.tx.pojo.People) context.getBean("peo");
System.out.println(p1);
Teacher teacher = (Teacher) context.getBean("teacher");
System.out.println(teacher);
Student stu = (Student) context.getBean("stu");
System.out.println(stu);
}
}
Spring-IOC-1注解
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- 打开Spring注解 -->
<mvc:annotation-driven />
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器@service是业务层 -->
<context:component-scan base-package="com.test.service" />
<bean id="addr" class="com.share.Addr">
<property name="pro" value="sichuan"></property>
</bean>
</beans>
package com.share;
import org.springframework.stereotype.Repository;
public class Addr {
public Addr(){
}
private String pro;
public String getPro() {
return pro;
}
public void setPro(String pro) {
this.pro = pro;
}
@Override
public String toString() {
return "Addr [pro=" + pro + "]";
}
}
package com.test.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.share.Addr;
/**
* @Service:把People类做为Bean对象,在Spring框架中,把该类作为服务层
* */
@Service
public class People {
private String name = "";
/**
* Addr的对象,作为People的内置对象
* */
@Autowired
private Addr addr;
public void fun(){
System.out.println(addr.getPro());
System.out.println(addr.toString());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.main;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.test.service.People;
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("config/spring-mvc.xml");
People p = context.getBean(People.class);
p.fun();
}
}
Spring-IOC-2
流程;
开发过程:
1、实现Dao层,login方法---返回true or false
2、service层,登录成功或失败之后的操作
3、controller层,导向处理
响应时:
1、controller层处理请求,在控制层中调用service层的方法获得处理结果,根据结果导向
2、调用service层方法时,调用Dao层的方法判断登录成功或失败
3、Dao层方法,连接资源库,获取用户数据
配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- contextConfigLocation:不能修改 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
配置spring-mvc.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!--第一步: 打开Spring注解 -->
<mvc:annotation-driven />
<!-- 开启SpringMVC的注解 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<!-- 包扫描:扫描@Controller, @Service, @Repository, @Component
@Controller:控制器注解
@Service:服务层注解
@Repository:DAO层注解
@Component:不好分层的类的注解
注解的类 -->
<context:component-scan base-package="com.share.service" />
<context:component-scan base-package="com.share.dao" />
<context:component-scan base-package="com.share.controller" />
<!-- 这里的class属性是固定写法 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--JstlView表示JSP模板页面需要使用JSTL标签库,classpath中必须包含jstl的相关jar包 -->
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<!-- 查找视图页面的前缀和后缀(前缀[逻辑视图名]后缀),比如传进来的逻辑 视图名为hello,则该jsp视图页面应该存放在“WEB-INF/jsp/hello.jsp” -->
<property name="prefix" value="/page/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
controller
package com.share.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.share.service.UserService;
@Controller
public class UserController {
private String SUCCESS = "success";
private String ERROR = "error";
/**
* @Autowired在系统中查找有无UserService类的对象,如果有,则把UserService类的对象赋给user.
* */
@Autowired
UserService user; //user = new UserServie()
@RequestMapping("/login")
public String userLogin(@RequestParam("name") String name, @RequestParam("pwd") String pwd){
String result = user.getUser(name, pwd);
if("登录成功".equals(result)){
return SUCCESS;
} else {
return ERROR;
}
}
}
dao
package com.share.dao;
import org.springframework.stereotype.Repository;
@Repository
public class UserDao {
public boolean isExitUser(String name, String pwd){
if("tangxin".equals(name) && "123".equals(pwd)){
return true;
} else {
return false;
}
}
}
service
package com.share.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import com.share.dao.UserDao;
@Service
public class UserService {
@Autowired
UserDao userDao;
public String getUser(String name, String pwd){
boolean exit = userDao.isExitUser(name, pwd);
return exit?"登录成功":"用户名或密码错误";
}
}
main
package com.share.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.share.service.UserService;
/**
* 开发过程中,检测spring配置是否正确,能否得到期待的结果
*/
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("config/spring-mvc.xml");
UserService userService = context.getBean(UserService.class);
String result = userService.getUser("tangxin", "123");
System.out.println(result);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="login?name=tangxin&pwd=123">用户登录</a>
</body>
</html>
Spring-IOC-3
配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- contextConfigLocation:不能修改 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
配置spring-mvc.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!--第一步: 打开Spring注解 -->
<mvc:annotation-driven />
<!-- 开启SpringMVC的注解 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<!-- 包扫描:扫描@Controller, @Service, @Repository, @Component
@Controller:控制器注解
@Service:服务层注解
@Repository:DAO层注解
@Component:不好分层的类的注解
注解的类 -->
<context:component-scan base-package="com.share.service" />
<context:component-scan base-package="com.share.dao" />
<context:component-scan base-package="com.share.controller" />
<!-- 这里的class属性是固定写法 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--JstlView表示JSP模板页面需要使用JSTL标签库,classpath中必须包含jstl的相关jar包 -->
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<!-- 查找视图页面的前缀和后缀(前缀[逻辑视图名]后缀),比如传进来的逻辑 视图名为hello,则该jsp视图页面应该存放在“WEB-INF/jsp/hello.jsp” -->
<property name="prefix" value="/page/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
controller
package com.share.controller;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.share.service.IBaseService;
import com.share.service.IUserService;
import com.share.service.UserService;
@Controller
public class UserController {
private String SUCCESS = "success";
private String ERROR = "error";
/**
* @Autowired在系统中查找有无IBaseService类的对象,如果有,则把UserService类的对象赋给user.
* */
//@Autowired
//@Resource(name="iuser")
//@Resource(type=IUserService.class)
//@Resource(name="iuser", type=IUserService.class)\
/*@Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按 byName自动注入罢了。
* @Resource有两个属性是比较重要的,分是name和type,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。
* 所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,
* 这时将通过反射机制使用byName自动注入策略。
@Resource装配顺序
1. 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;*/
@Resource(name="iuser")
IBaseService user;
@RequestMapping("/login")
public String userLogin(@RequestParam("name") String name, @RequestParam("pwd") String pwd){
/*if(user != null){
}*/
String result = user.getUser(name, pwd);
if("登录成功".equals(result)){
return SUCCESS;
} else {
return ERROR;
}
}
}
dao
package com.share.dao;
import org.springframework.stereotype.Repository;
@Repository(value="userdao")
public class UserDao {
public boolean isExitUser(String name, String pwd){
if("tangxin".equals(name) && "123".equals(pwd)){
return true;
} else {
return false;
}
}
}
service
package com.share.service;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.share.dao.UserDao;
@Service(value="iuser")
public class IUserService implements IBaseService {
//@Autowired
@Resource(name="userdao")
UserDao userDao;
@Override
public String getUser(String name, String pwd){
System.out.println("*******************");
boolean exit = userDao.isExitUser(name, pwd);
return exit?"登录成功":"用户名或密码错误";
}
}
package com.share.service;
public interface IBaseService {
public String getUser(String name, String pwd);
}
package com.share.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import com.share.dao.UserDao;
@Service(value="user")
public class UserService implements IBaseService {
@Autowired
UserDao userDao;
@Override
public String getUser(String name, String pwd){
System.out.println("=======================");
boolean exit = userDao.isExitUser(name, pwd);
return exit?"登录成功":"用户名或密码错误";
}
}
test
package com.share.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.share.service.UserService;
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("config/spring-mvc.xml");
UserService userService = context.getBean(UserService.class);
String result = userService.getUser("tangxin", "123");
System.out.println(result);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="login?name=tangxin&pwd=123">用户登录</a>
</body>
</html>
=========================================
=============================================
==================================================
Spring-AOP-Test
配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Spring-AOP-Test</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- contextConfigLocation:不能修改 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
配置spring-mvc.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- 表示将请求的URL和Bean名字映射,如URL为 “上下文/hello”, 则Spring配置文件必须有一个名字为“/hello”的Bean,上下文默认忽略。 -->
<bean
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<!-- 表示所有实现了org.springframework.web.servlet.mvc.Controller接口的Bean可以作为Spring
Web MVC中的处理器。 -->
<bean
class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
<bean name="/tx.do" class="com.tx.controller.MyController">
<property name="aspectTestService" >
<ref bean="AspectTestService"/>
</property>
</bean>
<!-- 这里的class属性是固定写法 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--JstlView表示JSP模板页面需要使用JSTL标签库,classpath中必须包含jstl的相关jar包 -->
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<!-- 查找视图页面的前缀和后缀(前缀[逻辑视图名]后缀),比如传进来的逻辑 视图名为hello,则该jsp视图页面应该存放在“WEB-INF/jsp/hello.jsp” -->
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
配置spring-aop.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- 进行AOP配置,proxy-target-class="true"表示允许使用CGLIB动态代理 -->
<aop:config proxy-target-class="true">
<!-- 注入切面类 -->
<aop:aspect id="TestAspect" ref="aspectBean" >
<!-- 定义切入点,execution(* com.tx.service.*.*(..))表示该包下所有类的所有方法都是切入点 -->
<aop:pointcut id="businessService" expression="execution(* com.tx.service.*.*(..))"/>
<!-- 定义通知以及要响应的切面方法 aop:before为前置通知,既切入点方法之前通知 -->
<aop:before pointcut-ref="businessService" method="doBefor"/>
</aop:aspect>
</aop:config>
<!-- 自己定义的切面类bean -->
<bean id="aspectBean" class="com.tx.aspect.TestAspect"/>
<!-- 自己定义的目标对象bean -->
<bean id="AspectTestService" class="com.tx.service.AspectTestService"/>
</beans>
-----
package com.tx.aspect;
import org.aspectj.lang.JoinPoint;
public class TestAspect {
public void doBefor(JoinPoint jp){
System.out.println("log Ending method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());
}
}
package com.tx.base;
public interface IBaseService {
public String methodA();
}
package com.tx.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.tx.service.AspectTestService;
public class MyController implements Controller{
private AspectTestService aspectTestService;
public AspectTestService getAspectTestService() {
return aspectTestService;
}
public void setAspectTestService(AspectTestService aspectTestService) {
this.aspectTestService = aspectTestService;
}
@Override
public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
// TODO Auto-generated method stub
System.out.println(aspectTestService.methodA());
return new ModelAndView("success");
}
}
package com.tx.service;
import com.tx.base.IBaseService;
public class AspectTestService implements IBaseService {
public String methodA() {
System.out.println("A方法被执行");
return "切入点A执行完毕";
}
}
package com.tx.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tx.service.AspectTestService;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext c = new ClassPathXmlApplicationContext("config/spring-aop.xml");
AspectTestService a = (AspectTestService) c.getBean("AspectTestService");
System.out.println(a.methodA());;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="tx.do">切面测试</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
成功界面
</body>
</html>
配置spring-aop.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- 配置前置控制器 -->
<bean id="aspectService" class="com.tx.service.AspectService" />
<!-- 配置“切入点” -->
<bean id="sleepAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice" ref="aspectService" />
<property name="pattern" value="com.tx.bean.*.*(..)" />
</bean>
<!-- 配置需要拦截的类 -->
<bean id="student" class="com.tx.bean.Student" />
<!-- spring中,配置AOP的固定写法 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
</beans>
package com.tx.bean;
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String say(String str){
System.out.println(name+":"+str);
return "真心话";
}
}
package com.tx.service;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import com.tx.bean.Student;
public class AspectService implements MethodBeforeAdvice, AfterReturningAdvice{
/**
* @param value 接收被拦截函数的返回值
* @param method 表示被拦截的方法
* @param parameter 表示被拦截方法的参数
* @param bean 拦截方法所在类的对象
* @see org.springframework.aop.AfterReturningAdvice#afterReturning(java.lang.Object, java.lang.reflect.Method, java.lang.Object[], java.lang.Object)
*/
@Override
public void afterReturning(Object value, Method method, Object[] parameter, Object bean) throws Throwable {
// TODO Auto-generated method stub
System.out.println("-----方法运行完毕后被调用------");
System.out.println("返回值:"+value);
System.out.println("方法:"+method.getName());
System.out.println("参数个数:"+parameter.length);
System.out.println("Student:"+((Student)bean).getName());
}
/**@param method 被拦截的方法
* @param parameter 被拦截方法中的参数
* @param bean 拦截方法所在类的对象
* @see org.springframework.aop.MethodBeforeAdvice#before(java.lang.reflect.Method, java.lang.Object[], java.lang.Object)
*/
@Override
public void before(Method method, Object[] parameter, Object bean) throws Throwable {
// TODO Auto-generated method stub
System.out.println("-----方法运行之前被调用------");
System.out.println(method.getName()+"已经被调用了");
System.out.println("方法参数个数为:"+parameter.length);
System.out.println("Student:"+((Student)bean).getName());
}
}
package com.tx.service;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tx.bean.Student;
public class Main {
public static void main(String[] args) {
ApplicationContext appCtx = new ClassPathXmlApplicationContext("config/spring-aop.xml");
Student stu = (Student) appCtx.getBean("student");
stu.setName("郑青青");
stu.say("唐老好帅");
}
}
SpringAOP-Annination
SpringAOP注解实现步骤:
1、导入SpringAOP支持注解的jar包
aopalliance.jar
asm-2.2.3.jar
asm-commons-2.2.3.jar
asm-util-2.2.3.jar
aspectjrt.jar
aspectjweaver.jar
cglib-nodep-2.1_3.jar
2、创建切面类: com.share.aspect.MyAspect.java。
并添加@Aspect切面类的注解
3、在切面类中创建通知(前置(befor),后置(after)),
语法格式: 配置前置通知。 后置通知的语法与前置通知相似,只需要把@Befor改成@After或@AfterReturning
@Before("execution(* com.share.controller.*.*(..))") //设置切点,
public void beforAdvic(){
System.out.println("初始化设置");
}
4、在spring的配置文件中完成配置。格式如下:
第一步:<!-- 启动@AspectJ支持:配置SpringAOP支持动态代理及AOP的注解方式 -->
<aop:aspectj-autoproxy/>
第二步:扫描被通知对象的类及切面类(创建切面对象,切点类的对象).
<!-- 包扫描:com.share.controller包, com.share.aspect下所有类都自动产生对象 -->
<context:component-scan base-package="com.share.controller, com.share.aspect">
<!-- 配置访问com.share.controller包下的切点时,都要经过(切面)动态代理 -->
<context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>
5、测试:
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("config/spring.xml");
UserController user = context.getBean(UserController.class);
user.getUser("666");
配置spring.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<!-- 包扫描:com.share.controller包, com.share.aspect下所有类都自动产生对象 -->
<context:component-scan base-package="com.share.controller, com.share.aspect">
<!-- 配置访问com.share.controller包下的切点时,都要经过(切面)动态代理 -->
<context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>
<!-- 启动@AspectJ支持:配置SpringAOP支持动态代理及AOP的注解方式 -->
<aop:aspectj-autoproxy/>
</beans>
package com.share.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect //注解切面类
public class MyAspect {
//@Befor 前置通知注解
@Before("execution(* com.share.controller.*.*(..))") //设置切点,
public void beforAdvic(JoinPoint jp){
//JoinPoint类对象,封装了切点函数的参数列表,方法名称,切点方法所在类的对象,
System.out.println(jp.getArgs().length); //目标方法的参数
System.out.println(jp.getSignature()); // 获取方法对象
System.out.println(jp.getTarget()); //获取切点方法所在类的对象
System.out.println(jp.getThis());
System.out.println("初始化设置");
}
//After: 后置通知
/*@After("execution(* com.share.controller.*.*(..))")
public void afterAdvic(JoinPoint jp){
//JoinPoint类对象,封装了切点函数的参数列表,方法名称,切点方法所在类的对象,
System.out.println(jp.getArgs().length); //目标方法的参数
System.out.println(jp.getSignature()); // 获取方法对象
System.out.println(jp.getTarget()); //获取切点方法所在类的对象
System.out.println(jp.getThis());
System.out.println("善后处理");
}*/
//@AfterReturning:后置于增强处理的通知,只能通过后置增加通知才能获取切点的返回值
//pointcat:设置切点, returning:获取切点函数的返回值
//returning的值与参数中的Object对数名称一致
@AfterReturning(pointcut = "execution(* com.share.controller.*.*(..))", returning = "rvt")
public void afterAdvic_1(JoinPoint jp, Object rvt){
//JoinPoint类对象,封装了切点函数的参数列表,方法名称,切点方法所在类的对象,
System.out.println(jp.getArgs().length); //目标方法的参数
System.out.println(jp.getSignature()); // 获取方法对象
System.out.println(jp.getTarget()); //获取切点方法所在类的对象
System.out.println(jp.getThis());
System.out.println(rvt);
System.out.println("善后处理");
}
}
package com.share.controller;
import org.springframework.stereotype.Controller;
@Controller
public class UserController {
public void getUser(String id){
System.out.println("获取用户对象");
}
}
package com.share.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.share.controller.UserController;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("config/spring.xml");
UserController user = context.getBean(UserController.class);
user.getUser("666");
}
}