注解实现AOP
<!--配置自动代理切面-->
<aop:aspectj-autoproxy/>
<!--配置扫描-->
<context:component-scan base-package=""></context:component-scan>
@Component("myAdvice")
@Aspect
public class MyAdvice{
/**@Before("execution(* service..*(..))")
public void before(){
System.out.println("添加事务");
}*/
//多处使用,可抽离为方法通过注解使用
@Pointcut("execution(* service..*(..))")
public void pointcut(){}
//注意:此处的aspectweaver.jar版本要在1.8以上
@Before("pointcut()")
public void before(){
System.out.println("添加事务");
}
}
Spring中提供的注解
Spring中的JdbcTemplate对象
概述:JdbcTemplate是Spring提供的对象,对原始的jdbc api进行的简单封装,存在与spring-jdbc.jar中
步骤:
-
4+1jar包
-
spring-jdbc.jar+spring-tx.jar spring对jdbc操作时需要事务的支持
-
创建JdbcTemplate对象,设置数据源,执行查询操作 (new BeanProperty…)
-
在xml中配置数据源
<bean id="dataSource" class="....DriverManagerDataSource">
<property name="" value=""></property>
<!--///代表简写-->
<property name="url" value="jdbc:mysql:///shop"></property>
<property name="" value=""></property>
<property name="" value=""></property>
</bean>
//需要使用JdbcDaoSupport中的setDataSource进行数据源的注入
public class UserDaoImpl extends JdbcDaoSupport implements UserDao{
//Autowired在方法上的使用,给参数进行注入
@Autowired
public void setDataSource(DataSource dataSource){
super.setDataSource(dataSource);
}
@Override
public List<User> queryUsers(){
return getJdbcTemplate().query("sql",new BeanPropertyRowMapper(User.class));
}
}
Spring对web的支持
步骤:使用servlet模拟处理登录请求
-
创建web项目导入4+1
-
导入spring-web.jar
-
创建jsp发送登录请求,使用servlet接收请求
-
创建service用于处理业务逻辑,在servlet中调用service对象
-
思考:servlet容器的创建和Spring容器的创建,该如何加载spring的配置文件
-
需要在web.xml中配置监听器ContextLoaderListener
-
在servlet中使用WebApplicationContext对象获取spring容器
@WebServlet("/user")
public class UserServlet{
@Override
public void service(.....){
String name = request.getParameter("username");
//获取Spring容器
WebApplicationContext wac =
(WebApplicationContext)request.getServletContext()
.getAttribute(WebApplicationContext.ROOT_WEB_APP...);
UserService service = wac.getBean("userService",UserService.class);
service.show(name);
}
}
执行后报错–在WEB-INF下找不到对应的配置文件,需要修改其默认的查找路径
<!--默认加载路径为/WEB-INF/applicationContext.xml
context-param:全局配置参数,指定加载路径
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置监听加载Spring容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Spring AOP与JdbcTemplate实战
本文详细介绍了如何在Spring框架中使用注解实现面向切面编程(AOP),并通过实例展示了JdbcTemplate对象在数据库操作中的应用。从配置自动代理切面到使用@Pointcut和@Before注解,再到JdbcTemplate的基本使用和数据源配置,最后探讨了Spring对Web的支持及整合。

被折叠的 条评论
为什么被折叠?



