一个初学者的学习笔记
文章目录
一、注解版与XML版的利弊
1.什么是Spring注解?
注解就是将原本需要在xml文件中进行注入的步骤,进行了封装整理,使得开发更高效,
常用的注解有:
@Autowired
@Repository dao层
@Service service层
@Controller
@Autowired 按照类型查找
结合@Qualifier注解完成按名称的注入。
@Resource 按照名称查找
@Value 注入普通类型属性
2.注解与XML版的利弊
使用spring的注解即有好处,也有坏处,虽然使用注解方式给类中的依赖属性赋值免去了java文件和.xml文件之间不断切换的操作,但是,spring的注解是和java文件放置在一块的,造成了两者粘性很强,违背了解耦合的理念。
3.ApsrctJ
- ApsrctJ是一个基于java语言的AOP框架
- Spring2.0之后新增了ApsrctJ切点表达式的支持
- 通过注解技术,允许在 Bean类中定义切面
二、正片开始
1.环境搭建
1.1导入所需要的jar包
1.2配置xml文件
这里直接利用 context 标签开启注解
并使用<aop:aspectj-autoproxy>标签开启AOP的注解
<?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="com.it.spring.aop1.dao"></context:component-scan>
<!--开启aop注解-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
2.具体实现
2.1编写目标类
dao层的接口和实现类
public interface UserDAO {
void addUser();
String addUser(int id);