2.spring
1.IoC/DI
-
导入依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.0.RELEASE</version> </dependency> <dependency> <!--lombok插件--> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency>
-
在spring容器中注入
<!--构造器注入--> <bean class="com.ujiuye.bean.User" name="user"> <constructor-arg name="id" value="1"/> <constructor-arg name="name" value="小红"/> <constructor-arg name="anminal" ref="anminal"/> <constructor-arg name="list"> <list> <value>aaa</value> <value>bbb</value> </list> </constructor-arg> <constructor-arg name="anminalList"> <list> <ref bean="anminal"/> <ref bean="anminal2"/> </list> </constructor-arg> </bean> <!--setter方式注入--> <bean class="com.ujiuye.bean.Anminal" name="anminal"> <property name="name" value="大黄"/> <property name="age" value="2"/> </bean> <bean class="com.ujiuye.bean.Anminal" name="anminal2"> <property name="name" value="旺财"/> <property name="age" value="5"/> </bean>
-
JavaBean
@Data@NoArgsConstructor@AllArgsConstructor public class Anminal implements Serializable { private String name; private Integer age; } @Data@NoArgsConstructor@AllArgsConstructor public class User implements Serializable { private Integer id; private String name; private Anminal anminal; private List<String> list; private List<Anminal> anminalList; }
-
-
在main方法中测试
public static void main(String[] args) { ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml"); User user = context.getBean(User.class); System.out.println(user); } out: User(id=1, name=小红, anminal=Anminal(name=大黄, age=2), list=[aaa, bbb], anminalList=[Anminal(name=大黄, age=2), Anminal(name=旺财, age=5)])
2.spring-test
- 导入依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
- 编写spring的测试类
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class App {
@Autowired
private User user;
@Test
public void test() throws Exception{
log.info("{}",user);
}
}
3.AOP准备知识
1.静态代理
- 真实类
public interface IUserService {
void sayHelo();
}
public class UserServiceImpl implements IUserService {
@Override
public void sayHelo() {
System.out.println("hello");
}
}
-
代理类
public class StaticProxy implements IUserService { @Override public void sayHelo() { new UserServiceImpl().sayHelo(); System.out.println("此处增强-------"); } }
-
测试
@Test public void testStaticProxy(){ IUserService service =new StaticProxy(); service.sayHelo(); }
2.动态代理
1.jdk动态代理(Java反射)
-
真实类(接口+实现类)
public interface IUserService { void sayHelo(); } public class UserServiceImpl implements IUserService { @Override public void sayHelo() { System.out.println("hello"); } }
-
代理类
public class MyHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { method.invoke(new UserServiceImpl(),args); System.out.println("此处增强-------"); return null; } }
-
测试
@Test public void testDynimalProxy(){ IUserService userService = (IUserService) Proxy.newProxyInstance(IUserService.class.getClassLoader(),UserServiceImpl.class.getInterfaces(), new MyHandler());//得到代理类 userService.sayHelo(); }
2.cglib动态代理(字节码)
-
准备(导入依赖)
<dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency>
-
真实类
public class StudentService { public void study(){ System.out.println("学习----"); } }
-
代理类
public class CglibProxy implements MethodInterceptor { @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { method.invoke(new StudentService(),objects); System.out.println("此处增强----"); return null; } }
-
测试
@Test
public void testCglibProxy() {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(StudentService.class);//设置父类
enhancer.setCallback(new CglibProxy());//设置回调
StudentService service = (StudentService)enhancer.create();//得到代理类
service.study();
}
3.AOP术语
pointcut:切入点(连接点集合 where)
joinpoint:连接点
advice:通知 (when+what)
aspect:切面(pointcut+advice)
4.AOP(xml)
-
导入依赖
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.2</version> </dependency>
-
编写切面类
@Slf4j public class UserServiceAspect { public void recordLog(){ log.info("{}","日志记录"); } public void checkRank(){ log.info("{}","权限检查"); } }
-
编写配置文件
<bean class="com.ujiuye.service.impl.UserServiceImpl" name="userService"/> <!--切面类--> <bean class="com.ujiuye.aspect.UserServiceAspect" name="aspect"/> <aop:config> <!--pointcut--> <aop:pointcut id="pc" expression="execution(* com.ujiuye.service..*(..))"/> <!--aspect--> <aop:aspect ref="aspect"> <!--前置增强--> <aop:before method="checkRank" pointcut-ref="pc"/> <!--最终增强--> <aop:after method="recordLog" pointcut-ref="pc"/> </aop:aspect> </aop:config>
-
测试
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class App {
@Autowired
private IUserService service;
@Test
public void test1() throws Exception{
service.sayHello();
}
}
5.AOP(注解版)
- 导入依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
-
logback.xml(日志文件)
<?xml version="1.0" encoding="UTF-8" ?> <configuration> <!--禁止logback默认显示的日志信息--> <statusListener class="ch.qos.logback.core.status.NopStatusListener" /> <!--定义一个带颜色的控制台输出日志PATTERN--> <property name="CONSOLE_LOG_PATTERN" value="时间:%date{yyyy-MM-dd HH:mm:ss} 级别: %highlight(%-5level) 进程: %boldYellow(%thread) 类: %boldGreen(%logger) 信息: %msg%n"/> <!--定义一个不带颜色的文件日志输出格式,因为文件不能带颜色--> <property name="ERRINFOFILE_LOG_PATTERN" value="时间:%date{yyyy-MM-dd HH:mm:ss} 级别: %-5level 进程: %thread 类: %logger 信息: %msg%n"/> <appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern> ${CONSOLE_LOG_PATTERN} </pattern> </layout> </appender> <root level="info"> <appender-ref ref="consoleLog" /> </root> </configuration>
-
编写切面类
@Slf4j
@Component
@Aspect
public class UserServiceAspect {
@Pointcut("execution(* com.ujiuye.spring.service..*(..))")
public void advice(){
}
@Around("advice()")
public Object recordLog(ProceedingJoinPoint point){
Object[] args = point.getArgs();
log.info("{}", Arrays.toString(args));
log.info("{}","开始日志--------");
Object object=null;
try {
object = point.proceed();
} catch (Throwable throwable) {
log.info("{}","异常日志--------");
}
log.info("{}","结束日志-------");
return object;
}
}
-
目标类及接口
public interface IUserService { User login(String username,String password); } @Slf4j @Service public class UserServiceImpl implements IUserService { public User login(String username, String password) { //模拟登录 if ("admin".equals(username)&&"123".equals(password)){ log.info("{}","登录成功"); return new User(); } return null; } }
-
编写配置类
@Configuration @ComponentScan("com.ujiuye.spring") @EnableAspectJAutoProxy public class ApplicationConfig { }
-
测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ApplicationConfig.class})
@Slf4j
public class App {
@Autowired
private IUserService userService;
@Test
public void test1() throws Exception{
User user = userService.login("admin", "123");
log.info("{}",user);
}
}