/**
* 通过IoC的方式获取User对象
* @return
*/
public static User getUserForIoC(){
// IoC的初始化操作
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// 从容器中获取User对象
User user = (User)ac.getBean("user");
return user;
}
// 可以通过bean 的name值获取
Student stu = (Student) ac.getBean("stu");
Student stu = (Student) ac.getBean("stuId");
Student stu = ac.getBean(Student.class);
Student stu = ac.getBean("stuId", Student.class);
id="stuId1,stuId2,stuId3"
表示bean有一个名字,就这个名字就叫stuId1,stuId2,stuId3
name="stu1,stu2,stu3"
表示bean有多个名字,分别是 stu1、stu2以及 stu3
public static void main(String[] args) {
// 创建IoC容器对象的时候就会初始化容器中管理的所有的Bean
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println("-----------");
// 去IoC容器中查找满足条件的对象
System.out.println(ac.getBean("stu1", Student.class));
// 创建IoC容器对象,BeanFactory仅仅只会加载解析配置文件,并不会创建具体的实例对象
System.out.println("*************************");
BeanFactory bf = new XmlBeanFactory(new
ClassPathResource("applicationContext.xml"));
System.out.println("------------");
// 去容器中根据条件获取对象,如果对象没有实例化那么就会创建该对象
System.out.println(bf.getBean("stu1",Student.class));
}
package com.bobo.ioc.factory;
import com.bobo.ioc.bean.User;
/**
* User 工厂类
*/
public class UserFactory {
/**
* 创建User对象
* 方法必须是static修饰
* @return
*/
public static User getInstance(){
return new User();
}
}
package com.bobo.ioc.factory;
import com.bobo.ioc.bean.User;
/**
* 动态工厂
*/
public class UserDynamicFactory {
public User getInstance(){
return new User();
}
}
package com.bobo.ioc.bean;
public class Cat {
// 昵称
private String nickName;
// 颜色
private String color;
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Cat{" +
"nickName='" + nickName + '\'' +
", color='" + color + '\'' +
'}';
}
}
package com.bobo.ioc.bean;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class UserBean {
// 编号
private Integer id;
// 拥有的对象
private Cat cat;
// List集合
private List games;
// 数组
private Cat[] cats;
// Map集合
private Map scores;
// Properties对象
private Properties properties;
public List getGames() {
return games;
}
public Map getScores() {
return scores;
}
public void setScores(Map scores) {
this.scores = scores;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public void setGames(List games) {
this.games = games;
}
public Cat[] getCats() {
return cats;
}
public void setCats(Cat[] cats) {
this.cats = cats;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
@Override
public String toString() {
return "UserBean{" +
"id=" + id +
", cat=" + cat +
'}';
}
}
LOL
DNF
WZRY
zhangsan
123456
package com.gupaoedu.ioc.bean;
public class User {
private Integer id;
private String userName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
'}';
}
}
package com.gupaoedu.ioc.dao;
import com.gupaoedu.ioc.bean.User;
/**
* User的Dao
*/
public interface IUserDao {
/**
* 获取User对象
* @return
*/
User getUser();
}
package com.gupaoedu.ioc.dao.impl;
import com.gupaoedu.ioc.bean.User;
import com.gupaoedu.ioc.dao.IUserDao;
public class UserDaoImpl implements IUserDao {
@Override
public User getUser() {
User user = new User();
user.setId(666);
user.setUserName("波波");
System.out.println("持久层...");
return user;
}
}
package com.gupaoedu.ioc.service;
import com.gupaoedu.ioc.bean.User;
/**
* User Service
*/
public interface IUserService {
/**
* 获取User对象
* @return
*/
User getUser();
}
package com.gupaoedu.ioc.service.impl;
import com.gupaoedu.ioc.bean.User;
import com.gupaoedu.ioc.dao.IUserDao;
import com.gupaoedu.ioc.dao.impl.UserDaoImpl;
import com.gupaoedu.ioc.service.IUserService;
/**
* User 的Service实现
*/
public class UserServiceImpl implements IUserService {
// 通过设值注入的方式做赋值 需要提供对应的setter方法
private IUserDao dao ;
@Override
public User getUser() {
System.out.println("业务逻辑层....");
return dao.getUser();
}
/**
* 设值注入必须要提供的方法
* @param dao
*/
public void setDao(IUserDao dao) {
this.dao = dao;
}
}
package com.gupaoedu.ioc.controller;
import com.gupaoedu.ioc.bean.User;
import com.gupaoedu.ioc.service.IUserService;
/**
* 控制层
*/
public class UserController {
private IUserService service;
public User queryUser(){
System.out.println("控制层...");
return service.getUser();
}
public void setService(IUserService service) {
this.service = service;
}
}
package com.gupaoedu.ioc;
import com.gupaoedu.ioc.controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppStart {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// 从IoC容器中获取UserController实例
UserController u = ac.getBean(UserController.class);
System.out.println(u.queryUser());
}
}
/**
* @Component 被该注解标识的Java会被SpringIoC容器加载
*/
@Component
public class UserBean {
}
package com.gupaoedu.ioc.bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @Component 被该注解标识的Java会被SpringIoC容器加载
*/
@Component
public class UserBean {
// 从IoC容器中获取一个Cat实例
//@Resource(name = "cat")
// 默认是根据类型查找的
@Autowired
@Qualifier("a111")
private Cat cat;
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
}
/**
* Java配置类
* 被@Configuration注解标注的Java类就是一个配置类
* 作用和 applicationContext.xml 是一样的
*/
@Configuration
public class JavaConfig {
/**
* 被@Bean注解修饰的方法 等价于
*
* 默认的name为方法的名称
* @return
*/
@Bean("abc")
public UserBean getUserBean(){
return new UserBean();
}
}
public class AppStart {
public static void main(String[] args) {
// 基于Java配置类的 IoC初始化
ApplicationContext ac = new AnnotationConfigApplicationContext(JavaConfig.class);
// 获取实例
UserBean user = ac.getBean("abc", UserBean.class);
System.out.println(user);
}
}
package com.bobo.ioc.config;
import com.bobo.ioc.bean.DataSource;
import com.bobo.ioc.bean.UserBean;
import org.springframework.context.annotation.*;
/**
* Java配置类
* 被@Configuration注解标注的Java类就是一个配置类
* 作用和 applicationContext.xml 是一样的
*/
@Configuration
// 设置扫描
//@ComponentScan(basePackages = {"com.bobo.ioc.bean"})
@ComponentScans(@ComponentScan(basePackages = "com.bobo.ioc.bean"))
public class JavaConfig {
/**
* 被@Bean注解修饰的方法 等价于
*
* 默认的name为方法的名称
* @return
*/
@Bean("abc")
public UserBean getUserBean(){
UserBean user = new UserBean();
return user;
}
}
@Configuration
@ComponentScans({
@ComponentScan(basePackages = {"com.gupaoedu.ioc.controller"}
,useDefaultFilters = false
,includeFilters = {@ComponentScan.Filter(value ={Controller.class})}
)
, @ComponentScan(basePackages =
{"com.gupaoedu.ioc.service.impl","com.gupaoedu.ioc.dao.impl"}
,useDefaultFilters = true
,excludeFilters = {@ComponentScan.Filter(value = Controller.class)})
})
public class JavaConfig {
}
package com.bobo.ioc.config;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class ConditionOnClass implements Condition {
/**
*
* @param conditionContext
* @param annotatedTypeMetadata
* @return
* true 表示条件成立
* false 表示条件不成立
*/
@Override
public boolean matches(ConditionContext conditionContext
, AnnotatedTypeMetadata annotatedTypeMetadata) {
try {
Class> aClass = conditionContext.getClassLoader()
.loadClass("com.bobo.ioc.bean.Person");
if(aClass != null){
return true;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return false;
}
}
/**
* 被@Bean注解修饰的方法 等价于
*
* 默认的name为方法的名称
* @return
*/
@Bean("abc")
@Conditional(ConditionOnClass.class) // 条件注解 决定是否将UserBean添加到IoC容器中
public UserBean getUserBean(){
UserBean user = new UserBean();
return user;
}
package com.bobo.ioc.bean;
/**
* 数据源对象
*/
public class DataSource {
private String url;
private String userName;
private String password;
public DataSource(String url, String userName, String password) {
this.url = url;
this.userName = userName;
this.password = password;
}
@Override
public String toString() {
return "DataSource{" +
"url='" + url + '\'' +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
'}';
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
/**
* 开发环境的数据源
* @return
*/
@Bean("ds")
@Profile("dev")
public DataSource devDataSource(){
return new DataSource("http://dev1:8888/","admin","123456");
}
/**
* 生产环境的数据源
* @return
*/
@Bean("ds")
@Profile("pro")
public DataSource proDataSource(){
return new DataSource("http://pro1:8888/","root","123456");
}
package com.bobo.ioc;
import com.bobo.ioc.bean.StudentBean;
import com.bobo.ioc.bean.UserBean;
import com.bobo.ioc.config.JavaConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AppStart {
public static void main(String[] args) {
/*// 基于Java配置类的 IoC初始化
ApplicationContext ac = new AnnotationConfigApplicationContext(JavaConfig.class);
// 获取实例
UserBean user = ac.getBean("abc", UserBean.class);
System.out.println(user);
System.out.println(ac.getBean(StudentBean.class));*/
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
// 设置对应的环境信息
ac.getEnvironment().setActiveProfiles("pro");
ac.register(JavaConfig.class);
ac.refresh();
System.out.println(ac.getBean("ds"));
}
}
@Configuration
public class JavaConfig {
@Bean
@Scope(value = "prototype")
//@Scope("singleton")
public UserBean userBean(){
return new UserBean();
}
}
/**
* 代理模式中的 公共接口
*/
public interface SomeService {
String doSome(String msg);
}
/**
* 代理模式中的 目标对象
*/
public class SomeServiceImpl implements SomeService {
@Override
public String doSome(String msg) {
System.out.println("目标对象执行了..." + msg);
return "hello:" + msg;
}
}
package com.bobo.aop.proxy;
import com.bobo.aop.service.SomeService;
/**
* 静态代理类
*/
public class SomeProxy implements SomeService {
private SomeService target;
public SomeProxy(SomeService target) {
this.target = target;
}
/**
* 代理对象实际执行的方法
* @param msg
* @return
*/
@Override
public String doSome(String msg) {
System.out.println("目标方法执行之前....");
// 让目标对象来执行核心业务
String res = target.doSome(msg);
System.out.println("目标对象执行之后");
return res.toUpperCase();
}
}
package com.bobo.aop;
import com.bobo.aop.proxy.SomeProxy;
import com.bobo.aop.service.SomeService;
import com.bobo.aop.service.impl.SomeServiceImpl;
public class AppStart {
public static void main(String[] args) {
// 获取目标对象
SomeService target = new SomeServiceImpl();
// 获取代理对象
SomeProxy proxy = new SomeProxy(target);
// 通过代理对象执行目标对象的方法
System.out.println(proxy.doSome("abc"));
}
}
package com.bobo.aop.service;
/**
* 代理模式中的 公共接口
*/
public interface SomeService {
String doSome(String msg);
}
package com.bobo.aop.service.impl;
import com.bobo.aop.service.SomeService;
/**
* 代理模式中的 目标对象
*/
public class SomeServiceImpl implements SomeService {
@Override
public String doSome(String msg) {
System.out.println("目标对象执行了..." + msg);
return "hello:" + msg;
}
}
package com.bobo.aop;
import com.bobo.aop.service.SomeService;
import com.bobo.aop.service.impl.SomeServiceImpl;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class AppStart {
public static void main(String[] args) {
// 获取目标对象
SomeService target = new SomeServiceImpl();
// 获取基于JDK的代理对象
SomeService proxy = (SomeService) Proxy.newProxyInstance(target.getClass().getClassLoader() // 获取一个类加载器
, target.getClass().getInterfaces() // 获取目标对象实现的所有的接口
, new InvocationHandler() { // 获取一个InvocationHandler实例
/**
* 代理对象执行的方法
* 会在该方法中调用目标对象的方法
* @param proxy
* @param method
* @param args
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxy
, Method method, Object[] args) throws Throwable {
System.out.println("目标对象执行之前...");
// 目标对象方法的执行
Object res = method.invoke(target, args[0]);
System.out.println("目标对象执行之后...");
return res;
}
}
);
// 调用代理对象中的相关方法
System.out.println(proxy.doSome("123456"));
}
}
/**
* 目标对象
* 目标对象没有实现任何的接口
*/
public class SomeServiceImpl {
public String doSome(String msg){
System.out.println("目标对象执行了..." + msg);
return "hello:" + msg;
}
}
package com.bobo.aop.proxy;
import com.bobo.aop.service.impl.SomeServiceImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* CGLIB工厂
*/
public class CglibProxy implements MethodInterceptor {
// 声明目标对象
private SomeServiceImpl target;
public CglibProxy(SomeServiceImpl target) {
this.target = target;
}
/**
* 对外提供用来创建代理对象的方法
* @return
*/
public SomeServiceImpl createProxy(){
// 创建增强器
Enhancer enhancer = new Enhancer();
// 指定父类
enhancer.setSuperclass(SomeServiceImpl.class);
// 指定回调接口对象
enhancer.setCallback(this);
// 返回创建的cglib代理对象
return (SomeServiceImpl) enhancer.create();
}
/**
* 和之前的JDK动态代理中的invoke方法类似
* @param o
* @param method
* @param objects
* @param methodProxy
* @return
* @throws Throwable
*/
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("目标对象执行之前...");
// 目标对象方法的执行
Object res = method.invoke(target, objects[0]);
System.out.println("目标对象执行之后...");
return res;
}
}
package com.bobo.aop;
import com.bobo.aop.proxy.CglibProxy;
import com.bobo.aop.service.impl.SomeServiceImpl;
public class AppStart {
public static void main(String[] args) {
// 获取目标对象
SomeServiceImpl target = new SomeServiceImpl();
// 获取CGLIB代理对象
SomeServiceImpl proxy = new CglibProxy(target).createProxy();
// 执行方法
System.out.println(proxy.doSome("abcd"));
}
}
package com.bobo.aop.service;
/**
* 公共接口
*/
public interface SomeService {
String doSome(String msg);
void say();
}
package com.bobo.aop.service.impl;
import com.bobo.aop.service.SomeService;
/**
* 目标对象
*/
public class SomeServiceImpl implements SomeService {
@Override
public String doSome(String msg) {
System.out.println("目标对象doSome执行了..." + msg);
return "Hello:" + msg;
}
@Override
public void say() {
System.out.println("目标对象say执行了..." + 1/0 );
}
}
package com.bobo.aop.advice;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* 前置通知类
*/
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {
/**
* 前置通知 抽取的公共代码
* @param method 目标对象的方法
* @param objects 目标对象的参数列表
* @param o 目标对象
* @throws Throwable
*/
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(method);
System.out.println(Arrays.toString(objects));
System.out.println(o);
System.out.println("前置通知执行了.....");
}
}
beforeAdvice
package com.bobo.aop;
import com.bobo.aop.service.SomeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppStart {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
SomeService some = ac.getBean("proxyFactoryBean",SomeService.class);
System.out.println(some);
System.out.println("************");
String obj = some.doSome("aaa");
System.out.println(obj);
System.out.println("----------");
some.say();
}
}
package com.bobo.aop.advice;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
/**
* 后置通知类
*/
public class MyAfterReturningAdvice implements AfterReturningAdvice {
/**
* 后置通知方法
* @param returnValue
* @param method
* @param args
* @param target
* @throws Throwable
*/
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("后置方法执行了。。。" + returnValue );
}
}
throwsAdvice
package com.bobo.aop.advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* 环绕通知类
*/
public class MyMethodInterceptor implements MethodInterceptor {
/**
* 环绕通知
* 可以修改返回结果
* @param invocation
* @return
* @throws Throwable
*/
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("目标对象执行之前....");
Object obj = invocation.proceed(); // 目标对象的调用
System.out.println("目标对象执行之后....");
if(obj != null && obj instanceof String){
return ((String) obj).toUpperCase();
}
return obj;
}
}
throwsAdvice
package com.bobo.aop.advice;
import org.springframework.aop.ThrowsAdvice;
/**
* 异常通知类
*/
public class MyThrowsAdvice implements ThrowsAdvice {
/**
* 异常通知
* @param ex
*/
public void afterThrowing(Exception ex){
System.out.println("异常通知执行了..." + ex.getStackTrace());
}
}
throwsAdvice
execution(
[modifiers-pattern] 访问权限类型
ret-type-pattern 返回值类型
[declaring-type-pattern] 全限定性类名
name-pattern(param-pattern) 方法名(参数名)
[throws-pattern] 抛出异常类型
)
package com.bobo.aop.service;
/**
* 公共接口
*/
public interface SomeService {
String doSome(String msg);
void say();
}
package com.bobo.aop.service.impl;
import com.bobo.aop.service.SomeService;
/**
* 目标对象
*/
public class SomeServiceImpl implements SomeService {
@Override
public String doSome(String msg) {
System.out.println("目标对象doSome执行了..." + msg);
return "Hello:" + msg;
}
@Override
public void say() {
System.out.println("目标对象say执行了..." + 1 / 0);
}
}
/**
* 切面类
* @Aspect 该注解标注的 Java类就是一个切面类
*/
@Aspect
public class MyAspect {
/**
* 前置通知
* 通过切入点表达式来使 通知和切入点关联
*/
//@Before(value = "execution(* com.bobo.aop.service.*.*(..))")
public void beforeMethod(){
System.out.println("前置通知");
}
}
package com.bobo.aop.config;
import com.bobo.aop.aspect.MyAspect;
import com.bobo.aop.service.SomeService;
import com.bobo.aop.service.impl.SomeServiceImpl;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy
public class JavaConfig {
@Bean
public SomeService someService(){
return new SomeServiceImpl();
}
@Bean
public MyAspect myAspect(){
return new MyAspect();
}
}
package com.bobo.aop;
import com.bobo.aop.service.SomeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppStart {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
SomeService service = ac.getBean(SomeService.class);
System.out.println(service);
service.doSome("aaaa");
System.out.println("-------------");
service.say();
}
}
/**
* 切面类
* @Aspect 该注解标注的 Java类就是一个切面类
*/
@Aspect
public class MyAspect {
/**
* 前置通知
* 通过切入点表达式来使 通知和切入点关联
*/
//@Before(value = "execution(* com.bobo.aop.service.*.*(..))")
public void beforeMethod(){
System.out.println("前置通知");
}
/**
* 后置通知
*/
//@AfterReturning(value = "execution(* com.bobo.aop.service.*.*(..))",returning = "msg")
public void afterReturningMethod(Object msg){
System.out.println("后置通知..." + msg);
}
}
/**
* 环绕通知
* @return
*/
//@Around(value = "execution(* com.bobo.aop.service.*.*(..))")
public Object aroundMethod(ProceedingJoinPoint pjp){
System.out.println("执行之前...");
// 执行目标对象的方法
Object proceed = null;
try {
proceed = pjp.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("执行之后...");
return proceed;
}
/**
* 异常通知
* @param ex
*/
@AfterThrowing(value = "execution(* com.bobo.aop.service.*.*(..))",throwing = "ex")
public void throwsMethod(Exception ex){
System.out.println("异常通知..." + ex);
}
/**
* 最终通知
* 只要切入点方法执行了,那么最终通知一定会执行
* 我们可以用来做一些资源回收等操作
*/
@After(value = "execution(* com.bobo.aop.service.*.*(..))")
public void afterMethod(){
System.out.println("最终通知...");
}
package com.bobo.aop.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
/**
* 切面类
* @Aspect 该注解标注的 Java类就是一个切面类
*/
public class MyAspect {
/**
* 前置通知
* 通过切入点表达式来使 通知和切入点关联
*/
public void beforeMethod(){
System.out.println("前置通知");
}
/**
* 后置通知
*/
public void afterReturningMethod(Object msg){
System.out.println("后置通知..." + msg);
}
/**
* 环绕通知
* @return
*/
public Object aroundMethod(ProceedingJoinPoint pjp){
System.out.println("执行之前...");
// 执行目标对象的方法
Object proceed = null;
try {
proceed = pjp.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("执行之后...");
return proceed;
}
/**
* 异常通知
* @param ex
*/
public void throwsMethod(Exception ex){
System.out.println("异常通知..." + ex);
}
/**
* 最终通知
* 只要切入点方法执行了,那么最终通知一定会执行
* 我们可以用来做一些资源回收等操作
*/
public void afterMethod(){
System.out.println("最终通知...");
}
}
package com.bobo.aop.dao.impl;
import com.bobo.aop.bean.User;
import com.bobo.aop.dao.IUserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
public class UserDaoImpl implements IUserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
private String sql;
@Override
public int addUser(User user) {
sql = "insert into t_user(username,address,gender)values(?,?,?)";
return jdbcTemplate.update(sql,user.getUsername(),user.getAddress(),user.getGender());
}
@Override
public int deleteUserById(Integer id) {
sql = "delete from t_user where id = ?";
return jdbcTemplate.update(sql,id);
}
@Override
public int updateUser(User user) {
sql = "update t_user set username=?,address=?,gender=? where id = ?";
return jdbcTemplate.update(sql,user.getUsername(),user.getAddress(),user.getGender(),user.getId());
}
@Override
public List queryList() {
sql = "select * from t_user";
return jdbcTemplate.query(sql,new BeanPropertyRowMapper(){
/**
* 每获取一行记录就会回调一次本方法
* @param rs
* @param rowNumber
* @return
* @throws SQLException
*/
@Override
public User mapRow(ResultSet rs, int rowNumber) throws SQLException {
// 我们自己将查询出来的这行记录转换为我们期望的Java对象
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setAddress(rs.getString("address"));
user.setGender(rs.getString("gender"));
return user;
}
});
}
@Override
public User queryUserById(Integer id) {
sql = "select * from t_user where id = ?";
Integer[] ids = {id};
List lists = jdbcTemplate.query(sql, ids, new BeanPropertyRowMapper() {
@Override
public User mapRow(ResultSet rs, int rowNumber) throws SQLException {
// 我们自己将查询出来的这行记录转换为我们期望的Java对象
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setAddress(rs.getString("address"));
user.setGender(rs.getString("gender"));
return user;
}
});
if(lists != null && lists.size() == 1){
return lists.get(0);
}
return null;
}
}
package com.bobo.aop.dao.impl;
import com.bobo.aop.bean.User;
import com.bobo.aop.dao.IUserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
public class UserDaoImpl implements IUserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
private String sql;
@Override
public int addUser(User user) {
sql = "insert into t_user(username,address,gender)values(?,?,?)";
return jdbcTemplate.update(sql,user.getUsername(),user.getAddress(),user.getGender());
}
@Override
public int deleteUserById(Integer id) {
sql = "delete from t_user where id = ?";
return jdbcTemplate.update(sql,id);
}
@Override
public int updateUser(User user) {
sql = "update t_user set username=?,address=?,gender=? where id = ?";
return jdbcTemplate.update(sql,user.getUsername(),user.getAddress(),user.getGender(),user.getId());
}
@Override
public List queryList() {
sql = "select * from t_user";
return jdbcTemplate.query(sql,new BeanPropertyRowMapper(){
/**
* 每获取一行记录就会回调一次本方法
* @param rs
* @param rowNumber
* @return
* @throws SQLException
*/
@Override
public User mapRow(ResultSet rs, int rowNumber) throws SQLException {
// 我们自己将查询出来的这行记录转换为我们期望的Java对象
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setAddress(rs.getString("address"));
user.setGender(rs.getString("gender"));
return user;
}
});
}
@Override
public User queryUserById(Integer id) {
sql = "select * from t_user where id = ?";
Integer[] ids = {id};
List lists = jdbcTemplate.query(sql, ids, new BeanPropertyRowMapper() {
@Override
public User mapRow(ResultSet rs, int rowNumber) throws SQLException {
// 我们自己将查询出来的这行记录转换为我们期望的Java对象
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setAddress(rs.getString("address"));
user.setGender(rs.getString("gender"));
return user;
}
});
if(lists != null && lists.size() == 1){
return lists.get(0);
}
return null;
}
}
package com.bobo.aop.service.impl;
import com.bobo.aop.bean.User;
import com.bobo.aop.dao.IUserDao;
import com.bobo.aop.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao dao;
/**
* @Transactional 表示开启事务
* @return
*/
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
@Override
public int fun1() {
// 添加数据
User user = new User();
user.setUsername("王五256");
user.setAddress("长沙256");
user.setGender("男");
// 添加用户信息
dao.addUser(user);
user.setId(5);
// 更新用户信息
dao.updateUser(user);
return 0;
}
}
ServiceA {
void methodA() {
ServiceB.methodB();
}
}
12345
ServiceB {
void methodB() {
}
}
1234
12345678910111213141516171819
12
12345
@Transactional(isolation=Isolation.DEFAULT)
public void fun(){
dao.add();
dao.udpate();
}
12345