纵有疾风起
人生不言弃

SpringBoot JDBC/AOP

JDBC

工程结构:

SpringBoot JDBC/AOP插图

pom.xml

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>com.example</groupId>    <artifactId>boot-jdbc</artifactId>    <version>0.0.1-SNAPSHOT</version>    <packaging>jar</packaging>    <name>boot-jdbc</name>    <description>Demo project for Spring Boot</description>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>2.0.6.RELEASE</version>        <relativePath/> <!-- lookup parent from repository -->    </parent>    <properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>        <java.version>1.8</java.version>    </properties>    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-jdbc</artifactId>        </dependency>        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>druid</artifactId>            <version>1.1.10</version>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>        </plugins>    </build></project>

实体类:

package com.example.bootjdbc.domain;import java.math.BigDecimal;import java.util.Date;public class Book {    private Integer bookId;    private String bookName;    private String bookAuthor;    private BigDecimal bookPrice;    private Date bookDate;    public Integer getBookId() {        return bookId;    }    public void setBookId(Integer bookId) {        this.bookId = bookId;    }    public String getBookName() {        return bookName;    }    public void setBookName(String bookName) {        this.bookName = bookName;    }    public String getBookAuthor() {        return bookAuthor;    }    public void setBookAuthor(String bookAuthor) {        this.bookAuthor = bookAuthor;    }    public BigDecimal getBookPrice() {        return bookPrice;    }    public void setBookPrice(BigDecimal bookPrice) {        this.bookPrice = bookPrice;    }    public Date getBookDate() {        return bookDate;    }    public void setBookDate(Date bookDate) {        this.bookDate = bookDate;    }    @Override    public String toString() {        return "Book{" +                "bookId=" + bookId +                ", bookName='" + bookName + '\'' +                ", bookAuthor='" + bookAuthor + '\'' +                ", bookPrice=" + bookPrice +                ", bookDate=" + bookDate +                '}';    }}

userDaoiml

package com.example.bootjdbc;import com.example.bootjdbc.domain.Book;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.RowMapper;import org.springframework.stereotype.Repository;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Date;import java.util.List;@Repositorypublic class UserDaoImpl {    @Autowired    private JdbcTemplate jdbcTemplate;    class BookRowMapper implements RowMapper<Book> {        @Override        public Book mapRow(ResultSet rs, int rowNum) throws SQLException {            Book book = new Book();            book.setBookAuthor(rs.getString("book_author"));            book.setBookDate(new Date(rs.getDate("book_date").getTime()));            book.setBookId(rs.getInt("book_id"));            book.setBookName(rs.getString("book_name"));            book.setBookPrice(rs.getBigDecimal("book_price"));            return book;        }    }    public void add() {        String sql = "INSERT INTO `testdb`.`t_book`(`book_name`, `book_author`, `book_price`, `book_date`) VALUES ('222', '333', 444, '2018-07-11');\n";        jdbcTemplate.execute(sql);    }    public Book selectOne() {        String sql = "select * from t_book where book_id=?";        Book book = jdbcTemplate.queryForObject(sql, new BookRowMapper(), 2);        return book;    }    public List<Book> selectList() {        String sql = "select * from t_book";        return jdbcTemplate.query(sql,new BookRowMapper());    }    public void update() {        String sql = "UPDATE `testdb`.`t_book` SET `book_name` = '333', `book_author` = '555', `book_price` = 444, `book_date` = '2018-07-11' WHERE `book_id` = 2;\n";        jdbcTemplate.update(sql);    }    public void delete() {        String sql = "delete from t_book where book_id=?";        jdbcTemplate.update(sql,3);    }}

测试类:

package com.example.bootjdbc;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.jdbc.core.JdbcTemplate;import javax.sql.DataSource;@SpringBootApplicationpublic class BootJdbcApplication {    public static void main(String[] args) throws Exception {        ConfigurableApplicationContext                context = SpringApplication.run(BootJdbcApplication.class, args);        System.out.println(context.getBean(DataSource.class).getClass());        DataSource dataSource = context.getBean(DataSource.class);        System.out.println(dataSource.getConnection().getCatalog());        System.out.println(context.getBean(JdbcTemplate.class));        System.out.println("--------------------------");        UserDaoImpl userDao = context.getBean(UserDaoImpl.class);        System.out.println(userDao.selectOne());        context.close();    }}

application.properties(默认配置HikariCP连接池)

spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql:///testdb?useSSL=truespring.datasource.username=rootspring.datasource.password=123# 通过type指定连接池类型spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

 

AOP

工程结构:

SpringBoot JDBC/AOP插图1

pom

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>com.example</groupId>    <artifactId>boot-aop</artifactId>    <version>0.0.1-SNAPSHOT</version>    <packaging>jar</packaging>    <name>boot-aop</name>    <description>Demo project for Spring Boot</description>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>2.0.6.RELEASE</version>        <relativePath/> <!-- lookup parent from repository -->    </parent>    <properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>        <java.version>1.8</java.version>    </properties>    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-aop</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>        </plugins>    </build></project>

application.properties

#spring.aop.auto = true##默认为false,根据有无接口来选择使用的代理方式,如果设置为true代表强制使用cglib代理方式##spring.aop.proxy-target-class=true

接口

package com.example.bootaop.dao;public interface BookDao {    void addBook(String name, String author);}
package com.example.bootaop.dao;import org.springframework.stereotype.Repository;@Repositorypublic class BookDaoImpl implements BookDao {    @Override    public void addBook(String name, String author) {        System.out.println("bookName:"+name+", bookAuthor:"+author);    }}
package com.example.bootaop.dao;import org.springframework.stereotype.Repository;@Repositorypublic class BookDaoImpl1 implements BookDao {    @Override    public void addBook(String name, String author) {    }}

切入类

package com.example.bootaop.aop;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.springframework.stereotype.Component;import java.util.Arrays;@Component@Aspectpublic class BookAop {    // 定义切入点    public static final String POINT_CUT = "execution(* com.example.bootaop.dao..*.*(..))";    @Before(POINT_CUT)    public void before() {        System.out.println("添加图书方法校验前.....");    }    @After(POINT_CUT)    public void after(JoinPoint jp) {        /// System.out.println(AopContext.currentProxy());        System.out.println(jp.getTarget().getClass());        System.out.println(Arrays.asList(jp.getArgs()));        System.out.println("添加图书成功后.....");    }}

测试类:

package com.example.bootaop;import com.example.bootaop.dao.BookDao;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.context.annotation.EnableAspectJAutoProxy;@SpringBootApplication@EnableAspectJAutoProxy(proxyTargetClass = false, exposeProxy = false)public class BootAopApplication {    public static void main(String[] args) {        ConfigurableApplicationContext                context = SpringApplication.run(BootAopApplication.class, args);        /*BookDaoImpl bookDao = context.getBean(BookDaoImpl.class);        System.out.println(bookDao.getClass());        bookDao.addBook("三国演义", "罗贯中");*/        BookDao bookDao = context.getBean("bookDaoImpl1",BookDao.class);        System.out.println(bookDao.getClass());        bookDao.addBook("三国演义", "罗贯中");        context.close();    }}

 

文章转载于:https://www.cnblogs.com/lm970585581/p/9839007.html

原著是一个有趣的人,若有侵权,请通知删除

未经允许不得转载:起风网 » SpringBoot JDBC/AOP
分享到: 生成海报

评论 抢沙发

评论前必须登录!

立即登录