一.Spring中的注解配置的一般姿势
1.导包
2.在主配置文件中引入新的命名空间
3.开启使用注解代理配置文件
4.在类中使用注解完成配置
二.注解实例
1.将对象注册到容器 这四种注解的方式实现的功能是一样的,没有本质的区别,后来开发人员为了区分各个层就约定在不同的层使用不同的注解。其实在各层使用任何一个注解都是可以的。使用注解就等价于在xml的配置。
2.修改对象的作用的范围
3.值类型注入方式
4.引用类型注入
5.初始化/销毁方法
javaBean
package com.auicyh.bean;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
//@Component("user")//<bean name="user" class="com.auicyh.bean.User"/>
//@Service("user")//service层
@Controller("user")//web层
//@Repository("user")//dao层
@Scope(scopeName="singleton")
//@Scope(scopeName="prototype")
public class User {
@Value("ydj")
private String name;
@Value(value="30")
private Integer age;
//@Autowired//自动装载对象属性
//@Qualifier("mini")//这两个注解加在一起相当于下面的一个
@Resource(name="car")
private Car car;
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public User() {
System.out.println("1.无参构造方法");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@PostConstruct//等价于xml配置中的init-method
public void init(){
System.out.println("生命周期属性之创建");
}
@PreDestroy//等价于xml配置中的destroy-method
public void destroy(){
System.out.println("生命周期属性之销毁");
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + ", car=" + car + "]";
}
}
package com.auicyh.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("car")
public class Car {
@Value("布加迪")
private String name;
@Value(value="black")
private String color;
@Override
public String toString() {
return "Car [name=" + name + ", color=" + color + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd ">
<!-- 指定扫描com.auicyh.bean包下的所有注解(子孙包全扫描)
-->
<context:component-scan base-package="com.auicyh.bean"></context:component-scan>
<bean name="mini" class="com.auicyh.bean.Car">
<property name="name" value="玛莎拉蒂"></property>
<property name="color" value="red"></property>
</bean>
</beans>
a.测试类-----注解方式创建对象
@Test
//测试注解方式创建对象
public void fun1(){
//1.创建容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.向容器要user对象
User user = (User) ac.getBean("user");
//3.打印输出
System.out.println(user);
}
测试结果
b.测试scope的范围
@Test
//测试Scope的范围
public void fun2(){
//1.创建容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.向容器要user对象
User user = (User) ac.getBean("user");
User user2 = (User) ac.getBean("user");
System.out.println(user==user2);//@Scope(scopeName="singleton") true
//@Scope(scopeName="prototype") false
//3.打印输出
System.out.println(user);
}
测试结果
c.测试生命周期属性
@Test
//测试注解的周期函数
public void fun3(){
//1.创建容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.向容器要user对象
User user = (User) ac.getBean("user");
//3.打印输出
System.out.println(user);
//4.销毁对象
((AbstractApplicationContext) ac).close();
}
测试结果
三.spring与junit整合测试
1.导包
2. 配置注解与测试
package com.auicyh.b_test;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.auicyh.bean.User;
//帮我们创建容器
@RunWith(SpringJUnit4ClassRunner.class)
//指定创建容器时使用哪个配置文件
@ContextConfiguration("classpath:applicationContext.xml")
//不用在每个方法中再创建容器和
public class Demo {
//引用类型的注解,手动注入指定注入哪个名称的对象
@Resource(name="user")
private User user;
@Test
//测试注解方式创建对象
public void fun1(){
//3.打印输出
System.out.println(user);
}
}
3.测试结果
四.spring aop
1.概念
2.spring实现aop的原理
UserService.java
package com.auicyh.service;
public interface UserService {
public void save();
public void delete();
public void update();
public void find();
}
UserServiceImpl.java
package com.auicyh.service.impl;
import com.auicyh.service.UserService;
public class UserServiceImpl implements UserService{
@Override
public void save() {
System.out.println("保存用户");
}
@Override
public void delete() {
System.out.println("删除用户");
}
@Override
public void update() {
System.out.println("更新用户");
}
@Override
public void find() {
System.out.println("查找用户");
}
}
a.动态代理实例
package com.auicyh.c_proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.auicyh.service.UserService;
import com.auicyh.service.impl.UserServiceImpl;
//观光代码=>动态代理
public class UserServiceProxyFactory implements InvocationHandler {
public UserServiceProxyFactory(UserService us) {
super();
this.us = us;
}
private UserService us;
public UserService getUserServiceProxy(){
//生成动态代理
UserService usProxy = (UserService) Proxy.newProxyInstance(UserServiceProxyFactory.class.getClassLoader(),
UserServiceImpl.class.getInterfaces(),
this);
//返回
return usProxy;
}
@Override
public Object invoke(Object arg0, Method method, Object[] arg2) throws Throwable {
System.out.println("打开事务!");
Object invoke = method.invoke(us, arg2);
System.out.println("提交事务!");
return invoke;
}
}
测试类
@Test
//动态代理
public void fun1(){
UserService us = new UserServiceImpl();
UserServiceProxyFactory factory = new UserServiceProxyFactory(us);
UserService usProxy = factory.getUserServiceProxy();
usProxy.save();
//代理对象与被代理对象实现了相同的接口
//代理对象 与 被代理对象没有继承关系
System.out.println(usProxy instanceof UserServiceImpl );//false
}
测试结果
b.cglib代理
package com.auicyh.c_proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import com.auicyh.service.UserService;
import com.auicyh.service.impl.UserServiceImpl;
//观光代码=>cglib代理
public class UserServiceProxyFactory2 implements MethodInterceptor {
public UserService getUserServiceProxy(){
Enhancer en = new Enhancer();//帮我们生成代理对象
en.setSuperclass(UserServiceImpl.class);//设置对谁进行代理
en.setCallback(this);//代理要做什么
UserService us = (UserService) en.create();//创建代理对象
return us;
}
@Override
public Object intercept(Object prxoyobj, Method method, Object[] arg, MethodProxy methodProxy) throws Throwable {
//打开事务
System.out.println("打开事务!");
//调用原有方法
Object returnValue = methodProxy.invokeSuper(prxoyobj, arg);
//提交事务
System.out.println("提交事务!");
return returnValue;
}
}
测试类
@Test
public void fun2(){
UserServiceProxyFactory2 factory = new UserServiceProxyFactory2();
UserService usProxy = factory.getUserServiceProxy();
usProxy.save();
//判断代理对象是否属于被代理对象类型
//代理对象继承了被代理对象=>true
System.out.println(usProxy instanceof UserServiceImpl );//true
}
测试结果
3.aop相关名词解释
五 spring 中aop实现的一般姿势
方式一 xml配置文件
1.导包
2.准备目标对象
3.准备通知
package com.auicyh.d_aspect;
import org.aspectj.lang.ProceedingJoinPoint;
//通知类
public class MyAdvice {
//前置通知
// |-目标方法运行之前调用
//后置通知(如果出现异常不会调用)
// |-在目标方法运行之后调用
//环绕通知
// |-在目标方法之前和之后都调用
//异常拦截通知
// |-如果出现异常,就会调用
//后置通知(无论是否出现 异常都会调用)
// |-在目标方法运行之后调用
//----------------------------------------------------------------
//前置通知
public void before(){
System.out.println("这是前置通知!!");
}
//后置通知
public void afterReturning(){
System.out.println("这是后置通知(如果出现异常不会调用)!!");
}
//环绕通知
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("这是环绕通知之前的部分!!");
Object proceed = pjp.proceed();//调用目标方法
System.out.println("这是环绕通知之后的部分!!");
return proceed;
}
//异常通知
public void afterException(){
System.out.println("出事啦!出现异常了!!");
}
//后置通知
public void after(){
System.out.println("这是后置通知(出现异常也会调用)!!");
}
}
4.将通知织入目标对象中
测试类
package com.auicyh.d_aspect;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.auicyh.bean.User;
import com.auicyh.service.UserService;
//帮我们创建容器
@RunWith(SpringJUnit4ClassRunner.class)
//指定创建容器时使用哪个配置文件
@ContextConfiguration("classpath:com/auicyh/d_aspect/applicationContext.xml")
//不用在每个方法中再创建容器和
public class Demo {
//引用类型的注解,手动注入指定注入哪个名称的对象
@Resource(name="userService")
private UserService userService;
@Test
//测试注解方式创建对象
public void fun1(){
userService.save();
}
}
测试结果
方式二 注解方式
1.导包(同方式一)
2.准备目标对象(同方式一)
3.准备通知
package com.auicyh.e_annotationaop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
//通知类
@Aspect//表示该类是一个通知类
public class MyAdvice {
//前置通知
// |-目标方法运行之前调用
//后置通知(如果出现异常不会调用)
// |-在目标方法运行之后调用
//环绕通知
// |-在目标方法之前和之后都调用
//异常拦截通知
// |-如果出现异常,就会调用
//后置通知(无论是否出现 异常都会调用)
// |-在目标方法运行之后调用
//----------------------------------------------------------------
//可以将注解的参数进行提取 简化代码
@Pointcut("execution(* com.auicyh.service.impl.*ServiceImpl.*(..))")
public void pc(){}
//前置通知
@Before("MyAdvice.pc()")
public void before(){
System.out.println("这是前置通知!!");
}
//后置通知
@AfterReturning("execution(* com.auicyh.service.impl.*ServiceImpl.*(..))")
public void afterReturning(){
System.out.println("这是后置通知(如果出现异常不会调用)!!");
}
//环绕通知
@Around("execution(* com.auicyh.service.impl.*ServiceImpl.*(..))")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("这是环绕通知之前的部分!!");
Object proceed = pjp.proceed();//调用目标方法
System.out.println("这是环绕通知之后的部分!!");
return proceed;
}
//异常通知
@AfterThrowing("execution(* com.auicyh.service.impl.*ServiceImpl.*(..))")
public void afterException(){
System.out.println("出事啦!出现异常了!!");
}
//后置通知
@After("execution(* com.auicyh.service.impl.*ServiceImpl.*(..))")
public void after(){
System.out.println("这是后置通知(出现异常也会调用)!!");
}
}
配置文件
测试类
package com.auicyh.e_annotationaop;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.auicyh.bean.User;
import com.auicyh.service.UserService;
//帮我们创建容器
@RunWith(SpringJUnit4ClassRunner.class)
//指定创建容器时使用哪个配置文件
@ContextConfiguration("classpath:com/auicyh/e_annotationaop/applicationContext.xml")
//不用在每个方法中再创建容器和对象
public class Demo {
//引用类型的注解,手动注入指定注入哪个名称的对象
@Resource(name="userService")
private UserService userService;
@Test
//测试注解方式创建对象
public void fun1(){
userService.save();
//3.打印输出
//System.out.println(userService);
}
}
测试结果