Spring01
TeamController.java
package com.kkb.controller;
import com.kkb.service.TeamService;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
@Repository
public class TeamController {
@Resource(/*name="teamService",type = TeamService.class*/) //JDK版本高于1.6 自动装配默认按照名称 但是如果名称没有相符的,就按照类型自动装配
private TeamService teamService;
public void add() {
teamService.add();
System.out.println("TeamController ------ add ------");
}
public TeamController() {
System.out.println("TeamController ---- 默认的构造方法");
}
}
MyFactory.java
package com.kkb.pojo;
public class MyFactory {
/**
* 实例方法
* @return
*/
public Team instanceFun() {
System.out.println("MyFactory----instanceFun");
return new Team(1003,"湖人","洛杉矶");
}
/**
* 静态方法
* @return
*/
public static Team staticFun() {
System.out.println("MyFactory----staticFun");
return new Team(1004,"小牛","达拉斯");
}
public static void main(String[] args) {
Team team1 = MyFactory.staticFun();
MyFactory factory = new MyFactory();
Team team = factory.instanceFun();
}
}
Team.java
package com.kkb.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 球队的实体类
*/
@Component
public class Team {
@Value("1001")
private Integer id;
@Value("潮人队")
private String name;
@Value("洛杉矶")
private String location;
public Team() {
System.out.println("Team - 默认的构造方法 id="+id+",name="+name+",location="+location);
}
public Team(Integer id, String name, String location) {
this.id = id;
this.name = name;
this.location = location;
System.out.println("Team - 带参数的构造方法 id="+id+",name="+name+",location="+location);
}
public void init() {
System.out.println("Team-init()-----");
}
public void destory() {
System.out.println("Team-destory()-----");
}
@Override
public String toString() {
return "Team{" +
"id=" + id +
", name='" + name + '\'' +
", location='" + location + '\'' +
'}';
}
@Value("1002")
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setLocation(String location) {
this.location = location;
}
}
TeamDao.java
package com.kkb.service;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
//@Component 注解标识在类上,表示对象由Spring容器创建 value属性表示创建的id值
// ,value可以省略,值也可以省略,默认就是类名的首字母小写
@Repository(value = "teamDao1")
//@Component(value = "teamDao")
//<bean id="teamDao" class="com.kkb.dao.TeamDao"></bean>
public class TeamDao {
public void add() {
System.out.println("TeamDao----add----");
}
public TeamDao() {
System.out.println("TeamDao ---- 默认的构造方法");
}
}
TeamService.java
package com.kkb.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("teamService")
public class TeamService {
@Autowired(required = true)//自动装配 默认按照类型装配 required=true(必须装配成功) required=false(装配不成功就为空指针)
//@Qualifier("teamDao1")//按照名称自动装配,需要Qualifier搭配使用
private TeamDao teamDao;//=new TeamDao();
public TeamService() {
System.out.println("TeamService ---- 默认的构造方法");
}
public TeamService(TeamDao teamDao) {
this.teamDao = teamDao;
}
public void add() {
teamDao.add();
System.out.println("TeamService----add----");
}
public TeamDao getTeamDao() {
return teamDao;
}
public void setTeamDao(TeamDao teamDao) {
this.teamDao = teamDao;
}
}
annotation.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"
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/beans ">
<!--表示告知spring 要扫描的包
这些包以及子包当中的类上如果添加了@Component注解,这些添加了注解的类就交给了spring容器的创建对象-->
<!--注意:在beans标签中添加 xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation += http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd-->
<!--多个包的扫描: 方式1:使用多个<context:component-scan 表明-->
<!-- <context:component-scan base-package="com.kkb.dao"></context:component-scan>-->
<!-- <context:component-scan base-package="com.kkb.service"></context:component-scan>-->
<!-- <context:component-scan base-package="com.kkb.controller"></context:component-scan>-->
<!--多个包的扫描:方式2: base-package中直接声明扫描的多个包,多个值用逗号、分号、空格(不推荐)分隔-->
<!-- <context:component-scan base-package="com.kkb.controller,com.kkb.service,com.kkb.dao"></context:component-scan>-->
<!--多个包的扫描:方式3: base-package中直接声明扫描的多个包的父包-->
<context:component-scan base-package="com.kkb"></context:component-scan>
</beans>
application.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--spring配置文件
beans:根标签
spring中Java的对象为java bean
spring-beans.xsd是一个约束文件 约束xml文件中都能编写哪些标签
-->
<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,告知spring容器创建哪些对象
一个bean标签标示一个对象
id="对象名",要求唯一值
class="完全限定名" spring底层是通过反射方式创建对象,不能写接口
相当于com.kkb.pojo.Team team1=new com.kkb.pojo.Team();然后将创建的对象放入spring容器的一个集合Map中
springMap.put(id,对象) 例如 springMap.put("team1",new Team());
scope="singleton:单例,默认值,容器启动完毕之后单例对象就被创建了,而且容器中只有唯一的一个对象
prototype:多例,多例的对象是什么时候创建,每次获取的时候都创建对象
lazy-init="true/false" 是否懒加载,针对单例对象
true:真懒 获取对象的是才创建对象
false:不懒 立即创建对象,不管是否使用
生命周期相关:
init-method="对象创建完毕之后立即调用的初始化方法
destroy-method="spring容器调用关闭方法的时候执行的方法
-->
<bean id="team1" class="com.kkb.pojo.Team" scope="singleton" lazy-init="true" init-method="init"
destroy-method="destory"></bean>
<bean id="team2" class="com.kkb.pojo.Team" scope="prototype"></bean>
<bean id="date1" class="java.util.Date"></bean>
</beans>
createType.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">
<!--spring容器创建对象的方式:
1、通过默认构造方法
2、通过带参数的构造方法
3、通过工厂方法:实例方法,静态方法
-->
<!--1、通过默认构造方法-->
<bean id="team1" class="com.kkb.pojo.Team"></bean>
<!--2、带参数的构造方法-->
<bean id="team2" class="com.kkb.pojo.Team">
<!--name:表示参数的名字-->
<constructor-arg name="id" value="1001" />
<constructor-arg name="name" value="勇士" />
<constructor-arg name="location" value="金州" />
</bean>
<bean id="team3" class="com.kkb.pojo.Team">
<!--index:表示参数的下标索引-->
<constructor-arg index="0" value="1002" />
<constructor-arg index="1" value="热火" />
<constructor-arg index="2" value="迈阿密" />
</bean>
<!--3、通过工厂方法-->
<!--3.1静态方法 Team team1 = MyFactory.staticFun();-->
<bean id="staticTeam" class="com.kkb.pojo.MyFactory" factory-method="staticFun"></bean>
<!--3.2实例方法 Team team = factory.instanceFun();-->
<bean id="factory" class="com.kkb.pojo.MyFactory"></bean>
<bean id="instanceFun" factory-bean="factory" factory-method="instanceFun"></bean>
</beans>
DL.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="teamDao" class="TeamDao"></bean>
<!--<bean id="teamDao1" class="TeamDao"></bean>-->
<bean id="teamService" class="com.kkb.service.TeamService">
<!--使用set方法注入属性值-->
<property name="teamDao" ref="teamDao"></property>
</bean>
<bean id="teamService2" class="com.kkb.service.TeamService" >
<!--使用构造方法注入属性值-->
<constructor-arg name="teamDao" ref="teamDao"></constructor-arg>
</bean>
<!--查询与属性值相同的容器中的对象,但是要求类型相同的对象唯一,否则抛出异常,不知道用哪一个匹配-->
<bean id="teamService3" class="com.kkb.service.TeamService" autowire="byName">
</bean>
<!--查询与属性值相同类型的容器中的对象,但是要求类型相同的对象唯一,否则抛出异常,不知道用哪一个匹配-->
<bean id="teamService4" class="com.kkb.service.TeamService" autowire="byType">
</bean>
</beans>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kkb</groupId>
<artifactId>spring01</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
CreateTypeTest
package com.kkb.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class CreateTypeTest {
@Test
public void test01() {
ApplicationContext ac = new ClassPathXmlApplicationContext("createType.xml");
}
}
Test01
package com.kkb.test;
import com.kkb.pojo.Team;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Date;
public class Test01 {
@Test
public void test02() {
String springConfig = "application.xml";
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(springConfig);
Team team1 = (Team) applicationContext.getBean("team1");
applicationContext.close();
}
@Test
public void test01() {
//Team team = new Team();//原有方法,程序员自己创建对象
//spring容器创建对象的方式
String springConfig = "application.xml";
// //获取容器
// ApplicationContext applicationContext =
//方式1:
//BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("E:/JavaTest/MySpring/spring01/src/main/resources/application.xml"));
//beanFactory.getBean("team1");//根据ID从IOC容器中获取对象
//方式2:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(springConfig);
//从容器中根据ID获取对象
Team team1 = (Team)applicationContext.getBean("team1");
//方式3:
//ApplicationContext applicationContext = new FileSystemXmlApplicationContext("E:/JavaTest/MySpring/spring01/src/main/resources/application.xml");
//容器中的其他API
int beanDefinitionCount = applicationContext.getBeanDefinitionCount();
System.out.println("容器中的对象的个数:"+beanDefinitionCount);
System.out.println("容器中所有对象的名称:");
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for(String name : beanDefinitionNames) {
System.out.println("\t"+name);
}
//4.获取非自定义的对象
Date date1 = (Date) applicationContext.getBean("date1");
System.out.println("获取非自定义的对象date="+date1);
}
}
Test02
package com.kkb.test;
import com.kkb.TeamDao;
import com.kkb.service.TeamService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test02 {
@Test
public void test02() {
ApplicationContext ac = new ClassPathXmlApplicationContext("DL.xml");
TeamService teamService = (TeamService) ac.getBean("teamService");
teamService.add();
TeamService teamService2 = (TeamService) ac.getBean("teamService2");
teamService2.add();
TeamService teamService3 = (TeamService) ac.getBean("teamService3");
teamService3.add();
TeamService teamService4 = (TeamService) ac.getBean("teamService4");
teamService4.add();
}
@Test
public void test01() {
TeamDao teamDao = new TeamDao();
TeamService teamService = new TeamService();
teamService.setTeamDao(teamDao);
teamService.add();
}
}
Test03
package com.kkb.test;
import com.kkb.controller.TeamController;
import com.kkb.pojo.Team;
import com.kkb.service.TeamService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test03 {
@Test
public void test01() {
ApplicationContext ac = new ClassPathXmlApplicationContext("annotation.xml");
/*Team team = (Team) ac.getBean("team");
System.out.println(team);*/
/*TeamService teamService = (TeamService) ac.getBean("teamService");
teamService.add();*/
TeamController teamController = (TeamController) ac.getBean("teamController");
teamController.add();
}
}
Spring02
AOP
package com.kkb.aop;
/**
* 切面:服务代码,切入到核心代码中,切入到哪里,给了四个位置
*/
public interface AOP {
void before();
void after();
void exception();
void myFinally();
}
LogAop
package com.kkb.aop;
public class LogAop implements AOP{
@Override
public void before() {
System.out.println("日志---before");
}
@Override
public void after() {
System.out.println("日志---after");
}
@Override
public void exception() {
System.out.println("日志---exception");
}
@Override
public void myFinally() {
System.out.println("日志---myFinally");
}
}
TranLAOP
package com.kkb.aop;
public class TranLAOP implements AOP{
@Override
public void before() {
System.out.println("事务---before");
}
@Override
public void after() {
System.out.println("事务---after");
}
@Override
public void exception() {
System.out.println("事务---exception");
}
@Override
public void myFinally() {
System.out.println("事务---myFinally");
}
}
CglibProxyFactory
package com.kkb.cglibproxy;
import com.kkb.aop.AOP;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CglibProxyFactory {
//目标对象
private NBAService nbaService;//没有实现接口的
//切面
private AOP aop;
public CglibProxyFactory() {
}
public CglibProxyFactory(NBAService nbaService, AOP aop) {
this.nbaService = nbaService;
this.aop = aop;
}
public Object getProxyInstance(NBAService nbaService, AOP aop) {
return Enhancer.create(nbaService.getClass(),
new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
try {
aop.before();
Object o1 = methodProxy.invokeSuper(o, objects);
aop.after();
return o1;
} catch (Exception e) {
aop.exception();
throw e;
} finally {
aop.myFinally();
}
}
});
}
}
MyCglibProxy
package com.kkb.cglibproxy;
import com.kkb.aop.AOP;
import com.kkb.aop.TranLAOP;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class MyCglibProxy {
public static void main(String[] args) {
//目标对象:没有接口
NBAService nbaService = new NBAService();
//创建切面
AOP tranAop = new TranLAOP();
//创建代理对象,选择cglib动态代理
NBAService proxyInstance = (NBAService) new CglibProxyFactory().getProxyInstance(nbaService, tranAop);
int res = proxyInstance.add("huren", 1001);
System.out.println(res);
}
public static void main1(String[] args) {
//目标对象:没有接口
NBAService nbaService = new NBAService();
//创建代理对象,选择cglib动态代理
NBAService proxyService = (NBAService) Enhancer.create(nbaService.getClass(),
new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
try {
System.out.println("开始事务");
Object invoke = methodProxy.invokeSuper(o, objects);
System.out.println("提交事务");
return invoke;
} catch (Exception e) {
System.out.println("事务回滚");
throw e;
} finally {
System.out.println("finally -------");
}
}
});
//代理对象干活
int res = proxyService.add("huren", 1001);
System.out.println(res);
}
}
NBAService
package com.kkb.cglibproxy;
public class NBAService {
public int add(String name,int id) {
System.out.println("NBAService ---- add ----");
return id;
}
}
MyJDKProxy
package com.kkb.dynamicproxy;
import com.kkb.aop.AOP;
import com.kkb.aop.LogAop;
import com.kkb.aop.TranLAOP;
import com.kkb.service.IService;
import com.kkb.service.TeamService;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MyJDKProxy {
public static void main(String[] args) {
//目标对象--被代理对象
TeamService teamService = new TeamService();
//切面
AOP tranAop = new TranLAOP();
AOP logAop = new LogAop();
//返回代理对象 基于JDK的动态代理
IService service = (IService) new ProxyFactory(teamService,tranAop).getProxyInstance();
IService service1 = (IService) new ProxyFactory(service,logAop).getProxyInstance();
//代理对象干活
service1.add();//核心业务+服务代码混合在一起的完整的业务方法
System.out.println(teamService.getClass());
System.out.println(service1.getClass()+"---------");
}
public static void main2(String[] args) {
//目标对象--被代理对象
TeamService teamService = new TeamService();
//切面
AOP tranAop = new TranLAOP();
//返回代理对象 基于JDK的动态代理
IService proxyService = (IService) Proxy.newProxyInstance(
teamService.getClass().getClassLoader(),
teamService.getClass().getInterfaces(),
new ProxyHandler(teamService,tranAop)
);
//代理对象干活
proxyService.add();
System.out.println(teamService.getClass());
System.out.println(proxyService.getClass()+"---------");
}
public static void main1(String[] args) {
//目标对象--被代理对象
TeamService teamService = new TeamService();
//返回代理对象 基于JDK的动态代理
IService proxyService = (IService) Proxy.newProxyInstance(
teamService.getClass().getClassLoader(),
teamService.getClass().getInterfaces(),
new InvocationHandler() {//回调函数 编写代理规则
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
System.out.println("开始事务");
Object invoke = method.invoke(teamService, args);//核心方法
System.out.println("提交事务");
return invoke;
}catch (Exception e) {
System.out.println("事务回滚");
e.printStackTrace();
throw e;
}finally {
System.out.println("finally--------");
}
}
}
);
//代理对象干活
proxyService.add();
System.out.println(teamService.getClass());
System.out.println(proxyService.getClass()+"---------");
}
}
ProxyFactory
package com.kkb.dynamicproxy;
import com.kkb.aop.AOP;
import com.kkb.service.IService;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyFactory {
private IService service;//目标对象
private AOP aop;//切面
public ProxyFactory(IService service, AOP aop) {
this.service = service;
this.aop = aop;
}
/**
* 获取动态代理的示例
* @return
*/
public Object getProxyInstance() {
return Proxy.newProxyInstance(
service.getClass().getClassLoader(),
service.getClass().getInterfaces(),
new InvocationHandler() {//回调函数 编写代理规则
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
aop.before();
Object invoke = method.invoke(service, args);//核心方法
aop.after();
return invoke;
}catch (Exception e) {
aop.exception();
e.printStackTrace();
throw e;
}finally {
aop.myFinally();
}
}
}
);
}
}
ProxyHandler
package com.kkb.dynamicproxy;
import com.kkb.aop.AOP;
import com.kkb.service.IService;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class ProxyHandler implements InvocationHandler {
private IService service;//目标对象
private AOP aop;//切面
public ProxyHandler(IService service, AOP aop) {
this.service = service;
this.aop = aop;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
aop.before();
Object invoke = method.invoke(service, args);//核心方法
aop.after();
return invoke;
}catch (Exception e) {
aop.exception();
e.printStackTrace();
throw e;
}finally {
aop.myFinally();
}
}
}
ProxyAOPService
package com.kkb.service.staticproxy;
import com.kkb.aop.AOP;
import com.kkb.service.IService;
public class ProxyAOPService implements IService {
private IService service;//被代理对象
private AOP aop;//要加入的切面
public ProxyAOPService(IService service, AOP aop) {
this.service = service;
this.aop = aop;
}
@Override
public void add() {
try{
aop.before();
service.add();
aop.after();
}catch (Exception e) {
aop.exception();
}finally {
aop.myFinally();
}
}
}
ProxyLogService
package com.kkb.service.staticproxy;
import com.kkb.service.IService;
public class ProxyLogService implements IService {
private IService service;//被代理对象
public ProxyLogService(IService service) {
this.service = service;
}
@Override
public void add() {
try {
System.out.println("开始日志");
service.add();
System.out.println("结束日志");
}catch (Exception e){
System.out.println("异常日志");
}
}
}
ProxyTeamService
package com.kkb.service.staticproxy;
import com.kkb.service.TeamService;
/**
* 基于类的静态代理
* 要求继承要被代理的类
* 弊端:每次只能代理一个类
*/
public class ProxyTeamService extends TeamService {
public void add() {
try {
System.out.println("开始事务");
super.add();//核心业务就是由被代理对象完成
System.out.println("提交事务");
}catch (Exception e){
System.out.println("回滚事务");
}
}
}
ProxyTranService
package com.kkb.service.staticproxy;
import com.kkb.service.IService;
/**
* 基于接口的静态代理
* 代理类和被代理类实现同一个接口
*/
public class ProxyTranService implements IService {
private IService service; //被代理的对象
public ProxyTranService(IService service) {
this.service = service;
}
@Override
public void add() {
try {
System.out.println("开始事务");
service.add();
System.out.println("提交事务");
}catch (Exception e){
System.out.println("回滚事务");
}
}
}
IService
package com.kkb.service;
/**
* 接口定义核心方法
*/
public interface IService {
void add();
}
TeamService
package com.kkb.service;
public class TeamService implements IService{
@Override
public void add() {
System.out.println("TeamService --- add ---");
}
/*public void add() {
try {
//System.out.println("开始事务");
System.out.println("TeamService --- add ---");//核心业务
//System.out.println("提交事务");
}catch (Exception e){
//System.out.println("回滚事务");
}
}*/
}
UserService
package com.kkb.service;
public class UserService implements IService {
@Override
public void add() {
System.out.println("UserService --- add ---");
}
}
Test01
package com.kkb.test;
import com.kkb.aop.AOP;
import com.kkb.aop.LogAop;
import com.kkb.aop.TranLAOP;
import com.kkb.service.IService;
import com.kkb.service.TeamService;
import com.kkb.service.UserService;
import com.kkb.service.staticproxy.ProxyAOPService;
import com.kkb.service.staticproxy.ProxyLogService;
import com.kkb.service.staticproxy.ProxyTranService;
import org.junit.Test;
public class Test01 {
@Test
public void test02() {
TeamService teamService = new TeamService();//被代理对象
AOP logAop = new LogAop();//切面-服务内容
AOP tranAop = new TranLAOP();
IService service1 = new ProxyAOPService(teamService,logAop);//代理对象--一级代理
IService service2 = new ProxyAOPService(service1,tranAop);//代理对象--二级代理
service2.add();
}
public static void main(String[] args) {
TeamService teamService = new TeamService();//被代理对象
UserService userService = new UserService();
ProxyTranService tranService = new ProxyTranService(userService);//事务代理对象--一级代理
//tranService.add();//代理对象干活,强强联合
ProxyLogService logService = new ProxyLogService(tranService);//日志的代理对象--二级代理
logService.add();
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kkb</groupId>
<artifactId>spring02</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.2</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
Spring03-aop
MyAOP
package com.kkb.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* 切面类
*/
@Component //切面对象的创建权限依然交给spring容器
@Aspect //aspect 框架的注解 标识当前类是一个切面类
public class MyAOP {
public void before(JoinPoint jp) {
System.out.println("AOP前置通知:在目标方法执行之前被调用的通知");
}
public void afterReturning(Object result) {
System.out.println("AOP后置通知:在目标方法执行之后被调用的通知");
}
public void exception(JoinPoint jp,Throwable ex) {
//一般会把异常发生的时间,位置,原因都记录下来
System.out.println("AOP异常通知:在目标方法执行出现异常的时候才会被调用的通知,否则不执行");
System.out.println(jp.getSignature()+"方法出现异常,异常信息是:"+ex.getMessage());
}
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("AOP环绕方法--目标方法的执行之前");
Object proceed = pjp.proceed();
System.out.println("AOP环绕方法--目标方法的执行之后");
return proceed;
}
public void myFinally() {
System.out.println("AOP最终通知:无论是否出现异常都是最后被调用的通知");
}
}
MyAspect
package com.kkb.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* 切面类
*/
@Component //切面对象的创建权限依然交给spring容器
//@Aspect //aspect 框架的注解 标识当前类是一个切面类
public class MyAspect {
/**
* PointCut 注解表示切入点表达式,方法一般声明为私有
* 其他的通知可以直接在value属性值直接可以使用方法名称
*/
@Pointcut("execution(* com.kkb.service..*.*(..))")
private void pointCut() {
}
@Before("pointCut()")
public void before(JoinPoint jp) {
System.out.println("前置通知:在目标方法执行之前被调用的通知");
String name = jp.getSignature().getName();
System.out.println("拦截的方法名称:"+name);
Object[] args = jp.getArgs();
System.out.println("方法的参数格式:"+args.length);
System.out.println("方法的参数列表:");
for(Object arg : args) {
System.out.println("\t" + arg);
}
}
/**
* AfterReturning 注解声明后置通知
* value: 表示切入点表达式
* returning 属性表示 返回的结果,如果需要的话可以在后置通知的方法中修改结果
*/
@AfterReturning(value = "execution(* com.kkb.service..*.update(..))",returning = "result")
public Object afterReturning(Object result) {
if(result!=null){
boolean res = (boolean)result;
if(res){
result = false;
}
System.out.println("后置通知:在目标方法执行之后被调用的通知,result="+result);
}
return result;
}
/**
* AfterReturning 注解声明异常通知方法
* value: 表示切入点表达式
* returning 属性表示 返回的结果,如果需要的话可以在后置通知的方法中修改结果
*/
@AfterThrowing(value = "execution(* com.kkb.service..*.*(..))",throwing = "ex")
public void exception(JoinPoint jp,Throwable ex) {
//一般会把异常发生的时间,位置,原因都记录下来
System.out.println("异常通知:在目标方法执行出现异常的时候才会被调用的通知,否则不执行");
System.out.println(jp.getSignature()+"方法出现异常,异常信息是:"+ex.getMessage());
}
/**
* Around 注解声明环绕通知
* ProceedingJoinPoint 中的proceed方法表示目标方法被执行
* @param pjp
* @return
* @throws Throwable
*/
@Around(value = "execution(* com.kkb.service..*.add*(..))")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕方法--目标方法的执行之前");
Object proceed = pjp.proceed();
System.out.println("环绕方法--目标方法的执行之后");
return proceed;
}
/**
* 注解声明为最终通知
*/
@After("execution(* com.kkb.service..*.*(..))")
public void myFinally() {
System.out.println("最终通知:无论是否出现异常都是最后被调用的通知");
}
}
IService
package com.kkb.service;
public interface IService {
void add(int id,String name);
boolean update(int num);
}
NBAService
package com.kkb.service;
import org.springframework.stereotype.Service;
@Service("nbaService")
public class NBAService implements IService{
@Override
public void add(int id, String name) {
System.out.println("TeamService --- add ---");
}
@Override
public boolean update(int num) {
System.out.println("NBAService --- update ---");
if(num>666){
return true;
}
return false;
}
}
TeamService
package com.kkb.service;
import org.springframework.stereotype.Service;
@Service
public class TeamService implements IService{
@Override
public void add(int id, String name) {
System.out.println("TeamService --- add ---");
}
@Override
public boolean update(int num) {
System.out.println("TeamService --- update ---");
if(num>666){
return true;
}
return false;
}
}
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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--在beans标签中引入 AOP和context约束-->
<context:component-scan base-package="com.kkb.service,com.kkb.aop"></context:component-scan>
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!--xml方式实现AOP-->
<aop:config>
<!--声明切入点的表达式,可以声明多个-->
<aop:pointcut id="pt1" expression="execution(* com.kkb.service..*.*(..))"/>
<aop:pointcut id="pt2" expression="execution(* com.kkb.service..*.add*(..))"/>
<aop:aspect ref="myAOP">
<aop:before method="before" pointcut-ref="pt1"></aop:before>
<aop:after-returning method="afterReturning" pointcut-ref="pt2" returning="result"></aop:after-returning>
<aop:after-throwing method="exception" pointcut-ref="pt1" throwing="ex"></aop:after-throwing>
<aop:after method="myFinally" pointcut-ref="pt1"></aop:after>
<aop:around method="around" pointcut-ref="pt2"></aop:around>
</aop:aspect>
</aop:config>
</beans>
Test01
package com.kkb.test;
import com.kkb.service.NBAService;
import com.kkb.service.TeamService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test01 {
@Test
public void test01() {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
TeamService teamService = (TeamService) ac.getBean("teamService");
teamService.add(1001,"潮人队");
System.out.println("-----");
boolean update = teamService.update(888);
System.out.println(update);
System.out.println("-----------------------------------");
NBAService nbaService = (NBAService) ac.getBean("nbaService");
nbaService.add(1002,"热火队");
System.out.println("-----");
boolean updat2 = nbaService.update(888);
System.out.println(updat2);
}
}
pom.xml
package com.kkb.test;
import com.kkb.service.NBAService;
import com.kkb.service.TeamService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test01 {
@Test
public void test01() {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
TeamService teamService = (TeamService) ac.getBean("teamService");
teamService.add(1001,"潮人队");
System.out.println("-----");
boolean update = teamService.update(888);
System.out.println(update);
System.out.println("-----------------------------------");
NBAService nbaService = (NBAService) ac.getBean("nbaService");
nbaService.add(1002,"热火队");
System.out.println("-----");
boolean updat2 = nbaService.update(888);
System.out.println(updat2);
}
}
Spring04-jdbc
TeamDao
package com.kkb.dao;
import com.kkb.pojo.Team;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
public class TeamDao extends JdbcDaoSupport {
public int getCount(){
String sql = "select count(id) from temp";
return this.getJdbcTemplate().queryForObject(sql,Integer.class);
}
public Map<String,Object> getMany(){
String sql = "select max(id),min(id) from temp";
return this.getJdbcTemplate().queryForMap(sql);
}
/**
* 自己封装一个处理结果的方法
* @param resultSet
* @return
* @throws SQLException
*/
public Team handlResult(ResultSet resultSet) throws SQLException {
Team team = new Team();
team.setId(resultSet.getInt("id"));
team.setName(resultSet.getString("name"));
return team;
}
public List<Team> findAll() {
String sql = "select * from temp";
return this.getJdbcTemplate().query(sql, new RowMapper<Team>() {
@Override
public Team mapRow(ResultSet resultSet, int i) throws SQLException {
return handlResult(resultSet);
}
});
}
public Team findById(int id) {
String sql = "select * from temp where id=?";
return this.getJdbcTemplate().queryForObject(sql, new Object[]{id}, new RowMapper<Team>() {
@Override
public Team mapRow(ResultSet resultSet, int i) throws SQLException {
Team team = new Team();
team.setId(resultSet.getInt("id"));
team.setName(resultSet.getString("name"));
return team;
}
});
}
public int insert(Team team) {
//使用JDBCTemplete
//JdbcTemplate template = new JdbcTemplate(dataSource);
String sql = "insert into temp(id,name) values(?,?)";
return this.getJdbcTemplate().update(sql,null,team.getName());
}
public int update(Team team) {
//使用JDBCTemplete
//JdbcTemplate template = new JdbcTemplate(dataSource);
String sql = "update temp set name=? where id=?";
return this.getJdbcTemplate().update(sql,team.getName(),team.getId());
}
public int del(Team team) {
//使用JDBCTemplete
//JdbcTemplate template = new JdbcTemplate(dataSource);
String sql = "delete from temp where id=?";
return this.getJdbcTemplate().update(sql,team.getId());
}
}
Team
package com.kkb.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 球队的实体类
*/
@Component
public class Team {
private Integer id;
private String name;
private String location;
public Team() {
}
public Team(String name) {
this.name = name;
}
@Override
public String toString() {
return "Team{" +
"id=" + id +
", name='" + name + '\'' +
", location='" + location + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
TeamService
package com.kkb.service;
import com.kkb.dao.TeamDao;
import com.kkb.pojo.Team;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class TeamService {
@Autowired
private TeamDao teamDao;
//@Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
public int insert(Team team) {
int num1 = teamDao.insert(team);
System.out.println("第一条执行结果:num1="+num1);
System.out.println(10/0);
int num2 = teamDao.insert(team);
System.out.println("第二条执行结果:num2="+num1);
return num1+num2;
}
}
application.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx.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.xsd
">
<context:component-scan base-package="com.kkb"></context:component-scan>
<!--创建 JdbcTemplate 的数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/javaweb?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!--创建 JdbcTemplate 的模版-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="teamDao" class="com.kkb.dao.TeamDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" /><!--isolation=""不写也行,默认进行回滚-->
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="pt" expression="execution(* com.kkb.service..*.*(..))"/>
<aop:advisor pointcut-ref="pt" advice-ref="txAdvice"/>
</aop:config>
<!--此处和代码里添加的注解相关-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
Test01
package com.kkb.test;
import com.kkb.dao.TeamDao;
import com.kkb.pojo.Team;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import java.beans.PropertyVetoException;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Test01 {
ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");
PlatformTransactionManager p;
TransactionDefinition t;
@Test
public void testGet() {
TeamDao dao = (TeamDao) ac.getBean("teamDao");
int count = dao.getCount();
System.out.println("查询的总行数:"+count);
Map<String, Object> many = dao.getMany();
Set<Map.Entry<String, Object>> entries = many.entrySet();
for (Map.Entry<String,Object> entry : entries){
System.out.println(entry.getKey()+"---"+entry.getValue());
}
}
@Test
public void testfindAll() {
TeamDao dao = (TeamDao) ac.getBean("teamDao");
List<Team> all = dao.findAll();
for(Team team : all){
System.out.println(team);
}
}
@Test
public void testfindById() {
TeamDao dao = (TeamDao) ac.getBean("teamDao");
Team team = dao.findById(1);
System.out.println(team);
}
@Test
public void testdelete() {
TeamDao dao = (TeamDao) ac.getBean("teamDao");
Team team = new Team();
team.setId(2);
int res = dao.del(team);
System.out.println("删除数据的结果:"+res);
}
@Test
public void testupdate() {
ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");
TeamDao dao = (TeamDao) ac.getBean("teamDao");
Team team = new Team();
team.setId(2);
team.setName("快船");
int res = dao.update(team);
System.out.println("更新数据的结果:"+res);
}
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");
TeamDao dao = (TeamDao) ac.getBean("teamDao");
Team team = new Team();
team.setName("快船");
int res = dao.insert(team);
System.out.println("插入数据的结果:"+res);
}
@Test
public void test01() throws PropertyVetoException {
//创建数据源
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/javaweb?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false");
dataSource.setUser("root");
dataSource.setPassword("123456");
//使用JDBCTemplete
JdbcTemplate template = new JdbcTemplate(dataSource);
String sql = "insert into temp(id,name) values(?,?)";
int update = template.update(sql,2,"勇士");
System.out.println("插入数据的结果:"+update);
}
}
Test02
package com.kkb.test;
import com.kkb.pojo.Team;
import com.kkb.service.TeamService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test02 {
@Test
public void test01() {
ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");
TeamService teamService = (TeamService) ac.getBean("teamService");
int num = teamService.insert(new Team("test"));
System.out.println(num);
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kkb</groupId>
<artifactId>spring04-jdbc</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--spring 核心依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
<!--测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!--编译插件-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>