Spring----06----注解AOP开发&&Spring整合JDBC(JDBCTemplate对象)

目录

  • Spring----06----注解AOP开发&&Spring整合JDBC(JDBCTemplate对象)
    • 1. 注解AOP开发
      • 1.1 使用注解注册bean
      • 1.2 配置切面
      • 1.3 使用全注解代替xml
    • 2. Spring整合JDBC(JDBCTemplate对象)
      • 2.1 导入spring-jdbc依赖
      • 2.2 书写实体类 | DAO
      • 2.3 准备Service
      • 2.4 配置xml
      • 2.5 测试
      • 2.6 使用JdbcDaoSupport类
      • 2.7 读取外部properties文件

Spring----06----注解AOP开发&&Spring整合JDBC(JDBCTemplate对象)

1. 注解AOP开发

1.1 使用注解注册bean

     applicationContext.xml中:

	
    <context:component-scan base-package="com.leo"/>

     使用注解注册通知对象:

//
@Component("myAdvice")
public class MyAdvice {

     使用注解注册目标对象:

//
@Service("userService")
public class UserServiceImpl implements UserSrevice{

1.2 配置切面

     先开启使用注解配置的开关:

    
    <aop:aspectj-autoproxy/>

     下面的配置代替了xml当中的aop:config元素:

//
@Component("myAdvice")
//@Aspect:声明要在该类中配置切面了
@Aspect
public class MyAdvice {

    //声明切点,方法名可在后续引用该切点
    @Pointcut("execution(* com.leo.*ServiceImpl.*(..))")
    public void myPC(){}
    
    //前置通知
    //@Before:前置切面
    @Before("myPC()")
    public void before(){
        System.out.println("前置通知");
    }

    //后置通知
    @AfterReturning("myPC()")
    public void after(){
        System.out.println("后置通知");
    }

    //异常通知
    @AfterThrowing("myPC()")
    public void afterThrowing(){
        System.out.println("异常通知");
    }

    //最终通知
    @After("myPC()")
    public void end(){
        System.out.println("最终通知");
    }

}
//环绕通知
@Component
@Aspect
public class MyAdvice2 {
    //环绕通知 => 在切点方法之前和之后都可以执行通知代码
    @Around("execution(* com.leo.*ServiceImpl.*(..))")
    public Object around(ProceedingJoinPoint pjp){
        Object o = null;
        //调用业务方法
        try {
            System.out.println("环绕通知--前置");
            o = pjp.proceed();//执行切点(业务)方法
            System.out.println("环绕通知--后置");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("环绕通知--异常");
        }finally {
            System.out.println("环绕通知--最终");
        }
        return o;
    }
}

1.3 使用全注解代替xml

     目前配置文件中还保留了一部分xml配置:

	
    <context:component-scan base-package="com.leo"/>

    
    <aop:aspectj-autoproxy/>

     其实可以将上面的两个配置,也使用注解来代替:

//声明该类是spring容器的配置类
@Configuration
//
@ComponentScan
//
@EnableAspectJAutoProxy
public class ApplicationContextConfiguration {
}

     测试:

@RunWith(SpringJUnit4ClassRunner.class)
//执行类类型的配置文件
@ContextConfiguration(classes = ApplicationContextConfiguration.class)
public class AopDemo5 {

    //配置完切面之后,获得目标对象时,其实会被替换为代理对象
    @Resource(name = "userService")
    private UserSrevice userSrevice;

    @Test
    public void fun1(){
        userSrevice.save();
    }

}

2. Spring整合JDBC(JDBCTemplate对象)

     可以理解为是Spring团队推出的DBUtils工具类。
     之前的DBUtils工具类是由Apache发布的。

2.1 导入spring-jdbc依赖

<dependencies>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.20version>
        dependency>
        
        <dependency>
            <groupId>com.mchangegroupId>
            <artifactId>c3p0artifactId>
            <version>0.9.5.5version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.2.8.RELEASEversion>
        dependency>
    dependencies>

2.2 书写实体类 | DAO

     实体类:

public class User {
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

}

     DAO:

public class UserDaoImpl implements UserDao{

    //作用相当于QuerryRunner
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    //update方法
    public void save(User user) {
        String sql = "insert into t_user values(null,?)";
        jdbcTemplate.update(sql, user.getName());
    }

    //update方法
    public void delete(Integer id) {
        String sql = "delete from t_user where id = ?";
        jdbcTemplate.update(sql,id);
    }

    //update方法
    public void update(User u) {
        String sql = "update t_user set name = ? where id = ?";
        jdbcTemplate.update(sql,u.getName(),u.getId());
    }

    //返回一个对象的查询
    public User findById(Integer id) {
        String sql = "select * from t_user where id = ?";
        User user = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),id);
        return user;
    }

    public List<User> findAll() {
        String sql = "select * from t_user";
        List<User> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<User>(User.class));
        return list;
    }

    public long findTotalCount() {
        String sql = "select count(*) from t_user";
        long count = jdbcTemplate.queryForObject(sql,long.class);
        return count;
    }
}

2.3 准备Service

@Service("userService")
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;

    public void regist(User user) {
        userDao.save(user);
    }
    public void delete(Integer id) {
        userDao.delete(id);
    }
    public void update(User user) {
        userDao.update(user);
    }
    public User findById(Integer id) {
        return userDao.findById(id);
    }
    public List<User> findAll() {
       return userDao.findAll();
    }
    public long findTotalCount() {
        return userDao.findTotalCount();
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

}

2.4 配置xml

     appliicationContext.xml:


        <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?serverTimezone=UTC"/>
            <property name="driverClass" value="com.mysql.jdbc.Driver"/>
            <property name="user" value="root"/>
            <property name="password" value="hanjuechen"/>
        bean>
        <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource"/>
        bean>
        
        <bean name="userDao" class="com.leo.dao.UserDaoImpl">
            <property name="jdbcTemplate" ref="jdbcTemplate">property>
        bean>
        
        <bean name="userService" class="com.leo.service.UserServiceImpl">
            <property name="userDao" ref="userDao">property>
        bean>

2.5 测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @Test
    public void testSave() {
        User u = new User();
        u.setName("brank");
        userService.regist(u);
    }
    @Test
    public void testDelete() {
        userService.delete(5);
    }
    @Test
    public void testupdate() {
        User u = new User();
        u.setId(1);
        u.setName("汤姆");
        userService.update(u);
    }
    @Test
    public void testFindById() {
        System.out.println(userService.findById(1));
    }
    @Test
    public void testFindAll() {
        System.out.println(userService.findAll());
    }
    @Test
    public void testFindTotalCount() {
        System.out.println(userService.findTotalCount());
    }
}

2.6 使用JdbcDaoSupport类

     修改Dao:

public class UserDaoImpl extends JdbcDaoSupport implements UserDao{
    //作用相当于QuerryRunner
    //private   getJdbcTemplate()   getJdbcTemplate();
    //update方法
    public void save(User user) {
        String sql = "insert into t_user values(null,?)";
        getJdbcTemplate().update(sql, user.getName());
	}

     修改xml配置:

	
      bean>
     -->
        
        <bean name="userDao" class="com.leo.dao.UserDaoImpl">
		
            <property name="dataSource"  ref="dataSource"/>
        bean>

2.7 读取外部properties文件

     准备db.properties配置:

jdbc.jdbcUrl=jdbc:mysql://localhost:3306/spring?serverTimezone=UTC
jdbc.driverClass=com.mchange.v2.c3p0.ComboPooledDataSource
jdbc.user=root
jdbc.password=hanjuechen

     applicationContext中配置读取properties:

		
        <context:property-placeholder location="classpath:db.properties">context:property-placeholder>

     连接池配置中引用properties中的键值对:

		
        <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
            <property name="driverClass" value="${jdbc.driverClass}"/>
            <property name="user" value="${jdbc.user}"/>
            <property name="password" value="${jdbc.password}"/>
        bean>

你可能感兴趣的:(SSM框架学习笔记,spring,aop,mysql,java)