目的:
利用SpringBoot做日志记录。
说明:
在面向切面编程AOP的思想里面,核心业务功能和切面功能分别独立进行开发,然后把切面功能和核心业务功能 “编织” 在一起,这就叫AOP。日志记录和核心业务功能分开,方便日志的管理维护。
实现步骤:
1. 核心代码
@Component("coreService")
public class CoreService {
public void coreMathod() {
// 仅仅只是实现了核心的业务功能
System.out.println("实现核心的业务功能");
}
2. 日志代码
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component
@Aspect
class Logger{
@Before("execution(* service.service())")
public void before(){
System.out.println("前置日志输出");
}
@After("execution(* service.service())")
public void after(){
System.out.println("后置日志输出");
}
}
3. applicationContext.xml 中配置自动注入,设置包名扫描这两个 Bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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="service" />
<context:component-scan base-package="logservice" />
<aop:aspectj-autoproxy/>
</beans>
4. 测试
public class Service01 extends ServiceEBase {
@Autowired
public CoreService coreService;
public EiInfo demoService() {
//ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/*.xml");
// ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//CoreService coreService= (CoreService ) context.getBean("coreService", CoreService .class);
// 也可以用自动注入 @Autowired
coreService.service();
}
}