【Java学习20170524】Spring

Spring总结


Spring
1、配置 ---声明JavaBean
第一种:在配置文件中,通过id匹配class来声明javaBean
第二种:在配置文件中,开启注解,设置注解所在的包,在对应的类添加注解
@Controller:控制器注解
@Service:服务层注解
@Repository:DAO层注解
@Component:不好分层的类的注解
2、声明切入点,创建通知

Spring-IOC-0

配置Spring.xml





	
	
		
		

		
		
		
		
	

	
		

		
		

	

	
		
		
	

	
		
		
		
		
		
		

		
		
		
		
		
		
	

	
		
		
		
		
	
	
		
		
	


 

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注解





	
	
	
	
	
	
	
		
	
	


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



  
  
    spring
    org.springframework.web.servlet.DispatcherServlet
    
    	
      contextConfigLocation
      classpath:config/spring-mvc.xml
    
    1
  
  
    spring
    /
  
  

配置spring-mvc.xml





	
	
	
	
	
	
	
	
	
	
	
	
	
	
		
		

		
		
		
	
	


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"%>




Insert title here


	用户登录


Spring-IOC-3


配置web.xml



	
		spring
		org.springframework.web.servlet.DispatcherServlet
		
			
			contextConfigLocation
			classpath:config/spring-mvc.xml
		
		1
	
	
		spring
		/
	

配置spring-mvc.xml





	
	
	
	
	
	
	
	
	
	
	
	
	
	
		
		

		
		
		
	
	

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"%>




Insert title here


	用户登录

=========================================

=============================================

==================================================

Spring-AOP-Test


配置web.xml



  Spring-AOP-Test
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
  
    spring
    org.springframework.web.servlet.DispatcherServlet
    
    	
      contextConfigLocation
      classpath:config/spring-*.xml
    
    1
  
  
    spring
    /
  
  

配置spring-mvc.xml




	
	
		
	
	




	
		
			
		
	


	
	
		
		

		
		
		
	


配置spring-aop.xml



        
	
	
		
		
			
			
			
			
		
	
	
	
	
	
	
	


-----

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"%>




Insert title here


	切面测试


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


	成功界面



Spring-AOP-Test2

配置spring-aop.xml




	
	
	

	
	
		
		
	
	
	
	
	

	
	
	


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的配置文件中完成配置。格式如下:
第一步:



第二步:扫描被通知对象的类及切面类(创建切面对象,切点类的对象).







5、测试:
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("config/spring.xml");
UserController user = context.getBean(UserController.class);
user.getUser("666");

配置spring.xml




	
	
		
		
	
	
	


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");
	}

}


你可能感兴趣的:(Java学习)